What is internal and external linking?

What is internal and external binding in C++?

Author: Abyx, 2016-02-09

1 answers

C++standard:

When a name has external linkage , the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit

And

When a name has internal linkage , the entity it denotes can be referred to by names from other scopes in the same translation unit.

In Russian, this can be translated as: external binding has those entities to which which can be accessed in a translation unit other than the one where they are defined. For example, having in the header header.h:

extern int object;

In first.cpp

int object;
...
object = 5;

In second.cpp

#include "header.h"
...
object = 3;

So, int object; in first.cpp it has an external binding, i.e. it can be referenced by other translation units, which it does second.cpp. But to second.cpp when he found out that such a variable even exists, we told him via extern int object;. Thus, it turns out that several translation units accesses the same object in memory. This is the external binding.

An internal binding differs from an external one in that an entity that has an internal binding cannot be accessed from a translation unit other than the one where it is defined. So, if you take the same example, but change first.cpp on

static int object;

Or on

namespace
{
    int object;
}

And do not touch the other code when linking second.cpp we will get a link builder error saying that it can't find object. This is because object has an internal binding and, as I said, this means that other translation units cannot see this name.


For a better understanding, we can use the following analogy: classes in C++ have several access levels, including private and public. The compiler checks that only the internal parts of the class (omitting friends and hacks) access the private members, and any access to them from outside the class will cause an error compilations. On the other hand, public members are accessible to everyone around them - they can be accessed by any external entity.

So, internal and external linking behave like private and public for classes, only errors are detected here at the linking stage, not compilation. In other words, it can also be said that entities with external binding are exported outside the translation unit, whereas those with internal binding are not, the outside world does not know about them at all.

 13
Author: ixSci, 2016-02-09 12:26:10