Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do classes have external linkage?

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?

like image 837
Vivek Avatar asked Jun 24 '11 08:06

Vivek


People also ask

What is external linkage?

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.

What are the types of linkages internal and external?

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.

What kind of linkage do static class functions have?

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.

What is true about external linkage in C?

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.


1 Answers

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.

like image 172
James Kanze Avatar answered Oct 04 '22 20:10

James Kanze