I want to understand the external linkage and internal linkage and their difference.
I also want to know the meaning of
const
variables internally link by default unless otherwise declared asextern
.
The linker goes through the compiled code and finds x and z first. As they are global variables, they are externally linked by default.
Explanation: There are three types of linkage in c++. They are an internal linkage, external linkage, and no linkage.
An identifier implementing internal linkage is not accessible outside the translation unit in which it is declared. An identifier with internal linkage denotes the same object or function within one translation unit if it is accessed by any function.
When you write an implementation file (.cpp
, .cxx
, etc) your compiler generates a translation unit. This is the source file from your implementation plus all the headers you #include
d in it.
Internal linkage refers to everything only in scope of a translation unit.
External linkage refers to things that exist beyond a particular translation unit. In other words, accessible through the whole program, which is the combination of all translation units (or object files).
As dudewat said external linkage means the symbol (function or global variable) is accessible throughout your program and internal linkage means that it is only accessible in one translation unit.
You can explicitly control the linkage of a symbol by using the extern
and static
keywords. If the linkage is not specified then the default linkage is extern
(external linkage) for non-const
symbols and static
(internal linkage) for const
symbols.
// In namespace scope or global scope. int i; // extern by default const int ci; // static by default extern const int eci; // explicitly extern static int si; // explicitly static // The same goes for functions (but there are no const functions). int f(); // extern by default static int sf(); // explicitly static
Note that instead of using static
(internal linkage), it is better to use anonymous namespaces into which you can also put class
es. Though they allow extern
linkage, anonymous namespaces are unreachable from other translation units, making linkage effectively static
.
namespace { int i; // extern by default but unreachable from other translation units class C; // extern by default but unreachable from other translation units }
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