| > | > | const has internal linkage in C++, but external linkage in C.
| > | Am I right ?
| > Yes.
.....
| > hth,
| > Ivan
|
| Hi,
| Can you please clarify me on external and internal linkage.
Well, Attila probably gave an explanation, but here's my throw at it.
External linkage = accessible from other compilation units (.cpp files).
Given the definition of a global variable with external linkage,
such as:
namespace n { int g; }
any other translation unit may access it by declaring the variable
again:
namespace n { extern int g; }
NB: for global variable declaration, 'extern' must be used to
explicitly specify that this is a declaration, but not
a definition(/"allocation") of the variable.
It also means that if another source file/library was to define a
global variable of the same name, an error will occur (typically
reported as a name collision at link time):
namespace n { int g; } // in a second file --> link error.
Static variables, as well as constants in namespace(=global) scope,
have internal linkage. It means that two translation units can
use a global variable that has the same name: the two variables
are allocated independently, or duplicated, and will not collide.
Internal/external linkage exists also for functions (e.g. static
non-member functions have internal linkage) and for classes (a
class defined in function scope is also currently said to have
internal linkage: it will not be accessible from the outside,
or collide with an identically named class in another function).
[ for classes IIRC, this might change in the next C++ standard,
to address the issue described in the next paragraph ].
Other than these usage aspects, the only real limitation of objects
that have internal linkage is that they cannot be used as template
parameters (~because of how link names are generated for templates).
This means that a predicate class used as a template parameter
cannot currently be defined within a function.
This limitation of objects with internal linkage is the main reason
why 'static' for global objects is considered to be deprecated.
The modern alternative is to use anonymous namespaces:
namespace { int g; } // external linkage, but never collides
During the compilation of each file, a unique 'prefix' is generated
for objects defined in an anonymous namespace.
They have external linkage, but will never "collide" because
of the unique prefix.
I hope you'll find these explanations useful,
Ivan