Do classes have external linkage? If so, why couldn’t I get the following to work on gcc?
// mycpp1.cpp
class MyClass
{
int x;
// ......
};
`
// mycpp2.cpp
class MyClass; // why doesn't this work?
I’ve done some googling around and came around this,
C++ Standard
(3.5/4) a named class (clause 9), or an unnamed class defined in a
typedef declaration in which the class has the typedef name for
linkage purposes (7.1.3);
I could just include the file, but what would be the purpose of linkage?
Why I half agree with Nawez that you shouldn’t worry too much about
linkage, it is nice to understand it, so you know why the coding pattern
you’re using works (and why other patterns don’t). Linkage defines how
a name (a symbol) is bound to an entity (variable, function, type,
etc.). External linkage means that the name (or the qualified version
of it) binds to the same entity in all of the translation units: in your
case, that
MyClassis the same class in all of the translation units.It doesn’t mean that all translation units automatically know how it is
defined; just that
MyClassinmycpp1.cppis the same type asMyClassinmycpp2.cpp. For various reasons related to compiler andlinker technology, you still have to provide a definition in every source
(preferably by means of an include) that uses it, but these definitions
are required to be identical (which is why the include is preferred),
because the compiler will generate code treating them as identical.