I have 2 files A.cpp and B.cpp which look something like
A.cpp
----------
class w
{
public:
w();
};
B.cpp
-----------
class w
{
public:
w();
};
Now I read somewhere (https://en.cppreference.com/w/cpp/language/static) that classes have external linkage. So while building I was expecting a multiple definition error but on the contrary it worked like charm. However when I defined class w in A.cpp, I got the redefinition error which makes me believe that classes have internal linkage.
Am I missing something here?
The term external linkage means that a symbol in one translation unit can be accessed from other translation units, whereas exporting refers to a symbol that is visible from a library file such as a DLL. Only external linkage symbols can be exported.
None linkage External Linkage-> means global, non-static variables and functions. Internal Linkage-> means static variables and functions with file scope. None Linkage-> means Local variables.
The static keyword, when used in the global namespace, forces a symbol to have internal linkage. The extern keyword results in a symbol having external linkage.
External Linkage: An identifier implementing external linkage is visible to every translation unit. Externally linked identifiers are shared between translation units and are considered to be located at the outermost level of the program.
Technically, as Maxim points out, linkage applies to symbols, not to the
entities they denote. But the linkage of a symbol is partially
determined by what it denotes: symbols which name classes defined at
namespace scope have external linkage, and w
denotes the same entity
in both A.cpp
and B.cpp
.
C++ has two different sets of rules concerning the definition of entities: some entities, like functions or variables, may only be defined once in the entire program. Defining them more than once will result in undefined behavior; most implementations will (most of the time, anyway) give a multiple definition error, but this is not required or guaranteed. Other entities, such as classes or templates, are required to be defined in each translation unit which uses them, with the further requirement that every definition be identical: same sequence of tokens, and all symbols binding to the same entity, with a very limited exception for symbols in constant expressions, provided the address is never taken. Violating these requirements is also undefined behavior, but in this case, most systems will not even warn.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With