According to the clause 3.5/4 of C++ Standard:
An unnamed namespace or a namespace declared directly or indirectly
within an unnamed namespace has internal linkage.
Simultanously in paragraph 7.3.1.1 we have note 96):
Although entities in an unnamed namespace might have external linkage,
they are effectively qualified by a name unique to their translation
unit and therefore can never be seen from any other translation unit.
How to explicitly make external linkage for name inside unnamed namespace and how to check that linkage is actually external if Standard guaranteed that there is no way to access name defined inside unnamed namespace from another translation unit?
In which cases doing explicit external linkage for name inside unnamed namespace is useful?
Re
” In which cases doing explicit external linkage for name inside unnamed namespace is useful?
The need for external linkage was important for C++03 templates. E.g. a function pointer as template argument had to be a pointer to function of external linkage. For example, the following would not compile with a C++03 compiler:
template< void(*f)() >
void tfunc() { f(); }
#include <stdio.h>
static void g() { printf( "Hello!\n" ); }
int main()
{
tfunc<g>();
}
It compiles fine with a C++11 compiler.
So, with C++11 the anonymous namespace mechanism for having external linkage yet no name conflicts between translation units, is only technically necessary for classes. A class has external linkage. One wouldn't want to have to choose class names that guaranteed did not occur in other translation units.
With C++11 the rules changed not only for template parameters, but for whether things in an anonymous namespace have external linkage or not. With C++03 an anonymous namespace had formally external linkage, possibly unless it is itself within an anonymous namespace (C++03 §3.5/4 last dash + C++03 §7.3.1.1/1). With C++11 an anonymous namespace has formally internal linkage.
This does not matter to the linker, because there's no linking of namespaces, but it matters as a formal device to describe linkage of things:
C++11 §3.5/4:
” An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. All other namespaces have external linkage. A name having namespace scope that has not
been given internal linkage above has the same linkage as the enclosing namespace if it is the name of
— a variable; or
— a function; or
— a named class (Clause 9), or an unnamed class defined in a typedef declaration in which the class has the typedef name for linkage purposes (7.1.3); or
— a named enumeration (7.2), or an unnamed enumeration defined in a typedef declaration in which the enumeration has the typedef name for linkage purposes (7.1.3); or
— an enumerator belonging to an enumeration with linkage; or
— a template.
Before going on to your other questions, it's worth noting that this quote from the standard,
” Although entities in an unnamed namespace might have external linkage, they are effectively qualified by a name unique to their translation unit and therefore can never be seen from any other translation unit.
is plain wrong, because an extern "C" entity is visible from other translation units regardless of what namespace it's declared in.
Happily, as I recall, notes are non-normative, i.e. they do not define the language.
Re
” How to explicitly make external linkage for name inside unnamed namespace
just declare a non-const variable, or a function, as extern.
you can declare a non-const variable, or a function, as extern "C", making the linkage extern but at the same time making the namespaces irrelevant as far as linking is concerned: the C language doesn't have them.
namespace {
extern "C" void foo() {} // Extern linkage
} // namespace <anon>
void bar() {} // Also extern linkage, but visible to other TUs.
Re
” how to check that linkage is actually external
well, the linkage affects things like possible conflicts with the One Definition Rule, often abbreviated as the “ODR”, which in C++11 is §3.2.
So, one way to see the linkage in action is to link two object files generated from the above source, as if you had two translation units with that same source code:
C:\my\forums\so\088> g++ -c anon.cpp -o x.o & g++ -c anon.cpp -o y.o
C:\my\forums\so\088> g++ main.cpp x.o y.o
y.o:anon.cpp:(.text+0x0): multiple definition of `foo'
x.o:anon.cpp:(.text+0x0): first defined here
y.o:anon.cpp:(.text+0x7): multiple definition of `bar()'
x.o:anon.cpp:(.text+0x7): first defined here
collect2.exe: error: ld returned 1 exit status
C:\my\forums\so\088> _
The linker complains about multiple definitions of foo, because as with C language binding it appears, as far as the linker is concerned, as a non-inline external linkage member of the global namespace, with two (possibly conflicting) definitions.
How to explicitly make external linkage for name inside unnamed namespace
The only way I can think of is to give it C language linkage, so that its linkage name ignores the namespace qualification:
namespace {
extern void f() { } // has internal linkage despite 'extern'
extern "C" void g() { } // ignores linkage of namespace
}
void (*p)() = f; // ensure 'f' won't be optimized away
(A strict reading of the standard suggests that g should have internal linkage, but that's not what compilers seem to do.)
and how to check that linkage is actually external if Standard guaranteed that there is no way to access name defined inside unnamed namespace from another translation unit?
Typically ELF compilers will implement internal linkage with non-global symbols, so you can compile the code and inspect the object file:
$ g++ -c linkage.cc
$ nm linkage.o
0000000000000000 t _ZN12_GLOBAL__N_11fEv
0000000000000007 T g
0000000000000000 D p
The mangled name of the unnamed namespace can vary between compilers, but demangling it will show:
$ nm -C linkage.o
0000000000000008 t (anonymous namespace)::f()
0000000000000000 T g
0000000000000000 D p
The lowercase t shows that f has local visibility, meaning it can't be linked to from other object files. The uppercase T shows that g has external linkage.
This isn't guaranteed by the standard though, as ELF visibility is not part of the C++ standard, and some compilers implement linkage without using visibility even on ELF platforms, e.g. the EDG compiler produces a global symbol for the same code:
$ nm linkage.o
0000000000000008 T _ZN23_GLOBAL__N__7_link_cc_p1fEv
0000000000000004 C __EDGCPFE__4_9
0000000000000000 T g
0000000000000000 D p
$ nm -C linkage.o
0000000000000008 T (anonymous namespace)::f()
0000000000000004 C __EDGCPFE__4_9
0000000000000000 T g
0000000000000000 D p
So using extern "C" allows you to give a name external linkage even if it appears in an unnamed namespace, but that doesn't make the note correct, because you can refer to that name from other translation units, because it doesn't use the unnamed namespace scope. That suggests to me that the note is simply a leftover from C++03 when entities in unnamed namespaces didn't automatically have internal linkage, and the note should be corrected or removed (and indeed T.C. points out it was already removed by DR 1603).
In which cases doing explicit external linkage for name inside unnamed namespace is useful?
I can't think of any cases where it's useful.
According to the standard[3.5/2]:
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.
So basically if you can refer to something in a translation unit different from the one where this something has been defined then it has external linkage, otherwise it has internal linkage. So given the note from the question:
Although entities in an unnamed namespace might have external linkage,
they are effectively qualified by a name unique to their translation
unit and therefore can never be seen from any other translation unit.
We practically have a situation in which we have a name but we don't know it, hence no matter how hard we try we can't refer to it from the different translation unit. And it makes it indistinguishable from the one with internal linkage. So, in my opinion it is just a word juggling — if you can't distinguish one situation from another then they are the same.
Related
I've read Translation units and linkage, and it says:
The concept of linkage applies only to global names. The concept of linkage does not apply to names that are declared within a scope. A scope is specified by a set of enclosing braces such as in function or class definitions.
It says "The concept of linkage applies only to global names" but didn't mention namespace scope. However, I saw namespace scope in some case we have to use extern to make some variables available in other files:
// constants.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace Constants
{
// since the actual variables are inside a namespace,
// the forward declarations need to be inside a namespace as well
extern const double pi;
extern const double avogadro;
extern const double my_gravity;
}
#endif
// constants.cpp
namespace Constants
{
// actual global variables
extern const double pi(3.14159);
extern const double avogadro(6.0221413e23);
extern const double my_gravity(9.2); // m/s^2 -- gravity is light on this planet
}
So what is the official definition? Is it true that linkage concept only apply to global, maybe namespace is part of global?
Namespaces are orthogonal to the distinction between global and local symbols. Namespaces just augment the name of a symbol, they don't change anything else. So, if you have a global variable, and put it inside a namespace it is still global variable, with external linkage.
The exception is when you put something inside an unnamed namespace. In this case, since there is no possible way code in one source file could reference a symbol in an unnamed namespace declared in another file, it is effectively a static symbol, and thus effectively has internal linkage.
Linkage applies to names basic.link/3:
A name is said to have linkage when it might denote the same object, reference, function, type, template, namespace or value as a name introduced by a declaration in another scope:
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.
When a name has module linkage, the entity it denotes can be referred to by names from other scopes of the same module unit ([module.unit]) or from scopes of other module units of that same module.
When a name has internal linkage, the entity it denotes can be referred to by names from other scopes in the same translation unit.
When a name has no linkage, the entity it denotes cannot be referred to by names from other scopes.
Names of variables at namespace scope have external linkage unless they meet certain exceptions. basic.link/5.8 For example, non-extern const variables at namespace scope have internal linkage. basic.link/4.2
And yes, global scope is a namespace scope. basic.scope.namespace/4
Here is the relevant section of the spec pertaining to linkage.
And a relevant snippet:
Indicating by default namespaces have external linkage, minus the exceptions given.
In C and C++ we can manipulate a variable's linkage. There are three kinds of linkage: no linkage, internal linkage, and external linkage. My question is probably related to why these are called "linkage" (How is that related to the linker).
I understand a linker is able to handle variables with external linkage, because references to this variable is not confined within a single translation unit, therefore not confined within a single object file. How that actually works under the hood is typically discussed in courses on operating systems.
But how does the linker handle variables (1) with no linkage and (2) with internal linkage? What are the differences in these two cases?
As far as C++ itself goes, this does not matter: the only thing that matters is the behavior of the system as a whole. Variables with no linkage should not be linked; variables with internal linkage should not be linked across translation units; and variables with external linkage should be linked across translation units. (Of course, as the person writing the C++ code, you must obey all of your constraints as well.)
Inside a compiler and linker suite of programs, however, we certainly do have to care about this. The method by which we achieve the desired result is up to us. One traditional method is pretty simple:
Identifiers with no linkage are never even passed through to the linker.
Identifiers with internal linkage are not passed through to the linker either, or are passed through to the linker but marked "for use within this one translation unit only". That is, there is no .global declaration for them, or there is a .local declaration for them, or similar.
Identifiers with external linkage are passed through to the linker, and if internal linkage identifiers are seen by the linker, these external linkage symbols are marked differently, e.g., have a .global declaration or no .local declaration.
If you have a Linux or Unix like system, run nm on object (.o) files produced by the compiler. Note that some symbols are annotated with uppercase letters like T and D for text and data: these are global. Other symbols are annotated with lowercase letters like t and d: these are local. So these systems are using the "pass internal linkage to the linker, but mark them differently from external linkage" method.
The linker isn't normally involved in either internal linkage or no linkage--they're resolved entirely by the compiler, before the linker gets into the act at all.
Internal linkage means two declarations at different scopes in the same translation unit can refer to the same thing.
No Linkage
No linkage means two declarations at different scopes in the same translation unit can't refer to the same thing.
So, if I have something like:
int f() {
static int x; // no linkage
}
...no other declaration of x in any other scope can refer to this x. The linker is involved only to the degree that it typically has to produce a field in the executable telling it the size of static space needed by the executable, and that will include space for this variable. Since it can never be referred to by any other declaration, there's no need for the linker to get involved beyond that though (in particular, the linker has nothing to do with resolving the name).
Internal linkage
Internal linkage means declarations at different scopes in the same translation unit can refer to the same object. For example:
static int x; // a namespace scope, so `x` has internal linkage
int f() {
extern int x; // declaration in one scope
}
int g() {
extern int x; // declaration in another scope
}
Assuming we put these all in one file (i.e., they end up as a single translation unit), the declarations in both f() and g() refer to the same thing--the x that's defined as static at namespace scope.
For example, consider code like this:
#include <iostream>
static int x; // a namespace scope, so `x` has internal linkage
int f()
{
extern int x;
++x;
}
int g()
{
extern int x;
std::cout << x << '\n';
}
int main() {
g();
f();
g();
}
This will print:
0
1
...because the x being incremented in f() is the same x that's being printed in g().
The linker's involvement here can be (and usually is) pretty much the same as in the no linkage case--the variable x needs some space, and the linker specifies that space when it creates the executable. It does not, however, need to get involved in determining that when f() and g() both declare x, they're referring to the same x--the compiler can determine that.
We can see this in the generated code. For example, if we compile the code above with gcc, the relevant bits for f() and g() are these.
f:
movl _ZL1x(%rip), %eax
addl $1, %eax
movl %eax, _ZL1x(%rip)
That's the increment of x (it uses the name _ZL1x for it).
g:
movl _ZL1x(%rip), %eax
[...]
call _ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_c#PLT
So that's basically loading up x, then sending it to std::cout (I've left out code for other parameters we don't care about here).
The important part is that the code refers to _ZL1x--the same name as f used, so both of them refer to the same object.
The linker isn't really involved, because all it sees is that this file has requested space for one statically allocated variable. It makes space for that, but doesn't have to do anything to make f and g refer to the same thing--that's already handled by the compiler.
My question is probably related to why these are called "linkage" (How is that related to the linker).
According to the C standard,
An identifier declared in different scopes or in the same scope more
than once can be made to refer to the same object or function by a
process called linkage.
The term "linkage" seems reasonably well fitting -- different declarations of the same identifier are linked together so that they refer to the same object or function. That being the chosen terminology, it's pretty natural that a program that actually makes linkage happen is conventionally called a "linker".
But how does the linker handle variables (1) with no linkage and (2) with internal linkage? What are the differences in these two cases?
The linker does not have to do anything with identifiers that have no linkage. Every such declaration of an object identifier declares a distinct object (and function declarations always have internal or external linkage).
The linker does not necessarily do anything with identifiers having internal linkage, either, as the compiler can generally do everything that needs to be done with these. Nevertheless, identifiers with internal linkage can be declared multiple times in the same translation unit, with those identifiers all referring to the same object or function. The most common case is a static function with a forward declaration:
static void internal(void);
// ...
static void internal(void) {
// do something
}
File-scope variables can also have internal linkage and multiple declarations that are all linked to refer to the same object, but the multiple declaration part is not as useful for variables.
In the standard it says that:
When a name has internal linkage , the entity it denotes can be
referred to by names from other scopes in the same translation unit.
and:
A name having namespace scope (3.3.6) has internal linkage if it is
the name of — a variable, function or function template that is
explicitly declared static;
So consider the following code:
#include <stdio.h>
namespace A
{
/* a with internal linkage now.
Entity denoted by a will be referenced from another scope.
This will be main() function scope in my case
*/
static int a=5;
}
int main()
{
int a; //declaring a for unqualified name lookup rules
printf("%d\n",a);//-1216872448
}
I really don't understand the definitions in the standard. What does it mean that:
the entity it denotes can be referred to by names from other scopes in
the same translation unit.
A translation unit usually consists of single source file with all #included files and results in one object file.
A name in namespace scope has by default external linkage, meaning you can refer that name from other translation units (with scope resolution operator or using directive). But if the name is qualified with static, the linkage becomes internal, and the name can not be referred outside the translation unit in which it was defined.
In your example you could access a if the namespace A, the name a and main method is in the same translation unit. But in main, you are declaring another variable a, which hides the a in namespace A. and the a in main is not initialized, so when you print, it actually prints garbage value from a declared in main. If you want to use a from A in main, use like cout<<A::a or use using namespace A; in the source file containing main.
"Translation unit" is the technical term for the chunk of code the compiler processes at one time. Usually this is a .cpp source file and all of the header files it includes.
In practice, this usually means that a translation unit gets compiled into an object file. This object file is not the complete program; it must be "linked" with other object files to make the final program. The "linking" process is simply matching up the various functions and such that are defined in one translation unit and used in one or more others.
For example, your translation unit calls printf, but the definition (machine code) for printf is actually in another translation unit. So the linker has to know 1) where the actual definition of printf is, and 2) where in your code it's called, so it can plug the address of 1) into 2).
printf is an example of something with external linkage; it can be linked to things external to its translation unit. On the flip side, something with internal linkage can only be linked within its translation unit. So, in your example, main can access A::a, which is declared static at the namespace level, but functions defined outside of this translation unit have no way of seeing A::a. This is because the compiler omits the reference to A::a from the link table in the object file.
Finally, what's happening in your example is that the a that main sees is the one it declared inside itself, which is uninitialized. That's why it's printing a garbage value. If you changed main to:
int main()
{
printf("%d\n", A::a);
}
it would print 5.
the entity it denotes can be referred to by names from other scopes in the same translation unit.
For this to make sense, you have to understand the difference between the entity and the name.
In your main function, you are creating a new entity and giving it the name a. The name does not refer to the same entity called a that is in namespace A. It's a different entity not only because it has different linkage, but also because it is in a different namespace.
Local variables have no linkage by default, and so they always specify a new entity. For example
static int a = 5; // a new entity with name `a` that has internal linkage.
int main()
{
int a; // This is a new entity local to function main with no linkage.
// It isn't initialized, so you have undefined behavior if you try to
// access it.
}
In this case, you have two entities, both named a, but they refer to different entities because they are in different scopes with different linkages.
The situation the standard is referring to is like this:
static int a = 5; // A new entity with the name `a` that has internal linkage.
void f()
{
extern int a; // This is a new declaration for the same entity called `a` in
// the global scope.
}
Now you only have one entity, but you still have two names in two different scopes. Those two names are referring to that same single entity.
This is a very tricky point. Because the declaration inside f() has extern, you are saying that you want f's a to refer to an entity that is defined elsewhere. However, since there is already a declaration for a at global scope that is declared static, it makes the a have internal linkage instead of external linkage.
Note that there isn't much practical value for having two names for the same entity with internal linkage since you can always just use the first name instead.
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 correct answer is yes, the name of a class may have external linkage. The previous answers are wrong and misleading. The code you show is legal and common.
The name of a class in C++03 can either have external linkage or no linkage. In C++11 the name of a class may additionally have internal linkage.
C++03
§3.5 [basic.link]
A name is said to have linkage when it might denote the same object,
reference, function, type, template, namespace or value as a name
introduced by a declaration in another scope
Class names can have external linkage.
A name having namespace scope has external linkage if it is the name
of
[...]
— a named class (clause 9), or an unnamed class defined in a typedef declaration in which the class has the typedef name for linkage
purposes (7.1.3)
Class names can have no linkage.
Names not covered by these rules have no linkage. Moreover, except as
noted, a name declared in a local scope (3.3.2) has no linkage. A name
with no linkage (notably, the name of a class or enumeration declared
in a local scope (3.3.2)) shall not be used to declare an entity with
linkage.
In C++11 the first quote changes and class names at namespace scope may now have external or internal linkage.
An unnamed namespace or a namespace declared directly or indirectly
within an unnamed namespace has internal linkage. All other namespaces
have external linkage. A name having namespace scope that has not been
given internal linkage above [class names were not] has the same linkage
as the enclosing namespace if it is the name of
[...]
— a named class (Clause 9), or an unnamed class defined in a typedef
declaration in which the class has the typedef name for linkage
purposes (7.1.3);
The second quote also changes but the conclusion is the same, class names may have no linkage.
Names not covered by these rules have no linkage. Moreover, except as
noted, a name declared at block scope (3.3.3) has no linkage. A type
is said to have linkage if and only if:
— it is a class or enumeration type that is named (or has a name for
linkage purposes (7.1.3)) and the name has linkage; or
— it is an unnamed class or enumeration member of a class with linkage;
Some of the answers here conflate the abstract notion of linkage in the C++ Standard with the computer program known as a linker. The C++ Standard does not give special meaning to the word symbol. A symbol is what a linker resolves when combining object files into an executable. Formally, this is irrelevant to the notion of linkage in the C++ Standard. The document only ever addresses linkers in a footnote regarding character encoding.
Finally, your example is legal C++ and is not an ODR violation. Consider the following.
C.h
----------
class w
{
public:
w();
};
A.cpp
-----------
#include "C.h"
B.cpp
-----------
#include "C.h"
Perhaps this looks familiar. After preprocessor directives are evaluated we are left with the original example. The Wikipedia link provided by Alok Save even states this as an exception.
Some things, like types, templates, and extern inline functions, can
be defined in more than one translation unit. For a given entity, each
definition must be the same.
The ODR rule takes content into consideration. What you show is in fact required in order for a translation unit to use a class as a complete type.
§3.5 [basic.def.odr]
Exactly one definition of a class is required in a translation unit if
the class is used in a way that requires the class type to be
complete.
edit - The second half of James Kanze's answer got this right.
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.
The class declaration
class w
{
public:
w();
};
does not produce any code or symbols, so there is nothing that could be linked and have "linkage". However, when your constructor w() is defined ...
w::w()
{
// object initialization goes here
}
it will have external linkage. If you define it in both A.cpp and B.cpp, there will be a name collision; what happens then depends on your linker. MSVC linkers e.g. will terminate with an error LNK2005 "function already defined" and/or LNK1169 "one or more multiply defined symbols found". The GNU g++ linker will behave similar. (For duplicate template methods, they will instead eliminate all but one instance; GCC docs call this the "Borland model").
There are four ways to resolve this problem:
If both classes are identical, put the definitions only into one .cpp file.
If you need two different, externally linked implementations of class w, put them into different namespaces.
Avoid external linkage by putting the definitions into an anonymous namespace.
namespace
{
w::w()
{
// object initialization goes here
}
}
Everying in an anonymous namespace has internal linkage, so you may also use it as a replacement for static declarations (which are not possible for class methods).
Avoid creating symbols by defining the methods inline:
inline w::w()
{
// object initialization goes here
}
No 4 will only work if your class has no static fields (class variables), and it will duplicate the code of the inline methods for each function call.
External linkage means the symbol (function or global variable) is accessible throughout your program and Internal linkage means that it's only accessible in one translation unit. you explicitly control the linkage of a symbol by using the extern and static keywords and the default linkage is extern for non-const symbols and static (internal) for const symbols.
A name with external linkage denotes an entity that can be referenced via names declared in the same scope or in other scopes of the same translation unit (just as with internal linkage), or additionally in other translation units.
The program actually violates the One Definition Rule but it is hard for the compiler to detect the error, because they are in different compilation units. And even the linker seems cannot detect it as an error.
C++ allows a workaround to bypass the One Definition Rule by making use of namespace.
[UPDATE] From C++03 Standard
§ 3.2 One definition rule, section 5 states:
There can be more than one definition of a class type ... in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then each definition of D shall consist of the same sequence of tokens.
Classes have no linkage to be pedantic.
Linkage only applies to symbols, that is, functions and variables, or code and data.
Seeing as you can't use static on a class, the only way to give a 'class' static linkage is to define the type in an anonymous namespace. Otherwise, it will have extern linkage. I put class in quotation marks because a class, which is a type, does not have a linkage, instead it is referring to the linkage of the symbols defined in the class scope (but not the linkage of an object made using the class). This includes static members and methods and non-static methods, but not non-static members as they are only part of the class type definition and do not additionally declare / define actual symbols.
The 'class' having static linkage means that the members and methods that would have had external linkage or external comdat linkage now both have static linkage only -- they are now local symbols, although the effect of inline at the compiler level still applies (i.e. it does not emit a symbol if it is not referenced in the translation unit) -- it's just no longer an external comdat symbol at assembler level, it's a local symbol. This is the case even if the member or method of the class is defined out-of-line and out of an anonymous namespace, it will still have static linkage.
If you declare the class type in an anonymous namespace, you will not be able to define the type outside of an anonymous namespace and it will not compile. You need to define it in the same anonymous namespace or a different anonymous namespace in the translation unit (different anonymous namespace doesn't matter because they're all combined into the same anonymous anonymous namespace name _GLOBAL__N_1).
This is the only way to change the linkage of members or methods of a class / struct because static will make it a static member and does not change the linkage, static will be ignored on out of line definitions, and extern is not allowed on class members / functions.
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 as extern.
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 #included 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 classes. 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
}
A global variable has external linkage by default. Its scope can be extended to files other than containing it by giving a matching extern declaration in the other file.
The scope of a global variable can be restricted to the file containing its declaration by prefixing the declaration with the keyword static. Such variables are said to have internal linkage.
Consider following example:
1.cpp
void f(int i);
extern const int max = 10;
int n = 0;
int main()
{
int a;
//...
f(a);
//...
f(a);
//...
}
The signature of function f declares f as a function with external linkage (default). Its definition must be provided later in this file or in other translation unit (given below).
max is defined as an integer constant. The default linkage for constants is internal. Its linkage is changed to external with the keyword extern. So now max can be accessed in other files.
n is defined as an integer variable. The default linkage for variables defined outside function bodies is external.
2.cpp
#include <iostream>
using namespace std;
extern const int max;
extern int n;
static float z = 0.0;
void f(int i)
{
static int nCall = 0;
int a;
//...
nCall++;
n++;
//...
a = max * z;
//...
cout << "f() called " << nCall << " times." << endl;
}
max is declared to have external linkage. A matching definition for max (with external linkage) must appear in some file. (As in 1.cpp)
n is declared to have external linkage.
z is defined as a global variable with internal linkage.
The definition of nCall specifies nCall to be a variable that retains its value across calls to function f(). Unlike local variables with the default auto storage class, nCall will be initialized only once at the first invocation of f(). The storage class specifier static affects the lifetime of the local variable and not its scope.
NB: The keyword static plays a double role. When used in the definitions of global variables, it specifies internal linkage. When used in the definitions of the local variables, it specifies that the lifetime of the variable is going to be the duration of the program instead of being the duration of the function.
In terms of 'C' (Because static keyword has different meaning between 'C' & 'C++')
Lets talk about different scope in 'C'
SCOPE: It is basically how long can I see something and how far.
Local variable : Scope is only inside a function. It resides in the STACK area of RAM.
Which means that every time a function gets called all the variables
that are the part of that function, including function arguments are
freshly created and are destroyed once the control goes out of the
function. (Because the stack is flushed every time function returns)
Static variable: Scope of this is for a file. It is accessible every where in the file
in which it is declared. It resides in the DATA segment of RAM. Since
this can only be accessed inside a file and hence INTERNAL linkage. Any
other files cannot see this variable. In fact STATIC keyword is the
only way in which we can introduce some level of data or function
hiding in 'C'
Global variable: Scope of this is for an entire application. It is accessible form every
where of the application. Global variables also resides in DATA segment
Since it can be accessed every where in the application and hence
EXTERNAL Linkage
By default all functions are global. In case, if you need to
hide some functions in a file from outside, you can prefix the static
keyword to the function. :-)
Before talking about the question, it is better to know the term translation unit, program and some basic concepts of C++ (actually linkage is one of them in general) precisely. You will also have to know what is a scope.
I will emphasize some key points, esp. those missing in previous answers.
Linkage is a property of a name, which is introduced by a declaration. Different names can denote same entity (typically, an object or a function). So talking about linkage of an entity is usually nonsense, unless you are sure that the entity will only be referred by the unique name from some specific declarations (usually one declaration, though).
Note an object is an entity, but a variable is not. While talking about the linkage of a variable, actually the name of the denoted entity (which is introduced by a specific declaration) is concerned. The linkage of the name is in one of the three: no linkage, internal linkage or external linkage.
Different translation units can share the same declaration by header/source file (yes, it is the standard's wording) inclusion. So you may refer the same name in different translation units. If the name declared has external linkage, the identity of the entity referred by the name is also shared. If the name declared has internal linkage, the same name in different translation units denotes different entities, but you can refer the entity in different scopes of the same translation unit. If the name has no linkage, you simply cannot refer the entity from other scopes.
(Oops... I found what I have typed was somewhat just repeating the standard wording ...)
There are also some other confusing points which are not covered by the language specification.
Visibility (of a name). It is also a property of declared name, but with a meaning different to linkage.
Visibility (of a side effect). This is not related to this topic.
Visibility (of a symbol). This notion can be used by actual implementations. In such implementations, a symbol with specific visibility in object (binary) code is usually the target mapped from the entity definition whose names having the same specific linkage in the source (C++) code. However, it is usually not guaranteed one-to-one. For example, a symbol in a dynamic library image can be specified only shared in that image internally from source code (involved with some extensions, typically, __attribute__ or __declspec) or compiler options, and the image is not the whole program or the object file translated from a translation unit, thus no standard concept can describe it accurately. Since symbol is not a normative term in C++, it is only an implementation detail, even though the related extensions of dialects may have been widely adopted.
Accessibility. In C++, this is usually about property of class members or base classes, which is again a different concept unrelated to the topic.
Global. In C++, "global" refers something of global namespace or global namespace scope. The latter is roughly equivalent to file scope in the C language. Both in C and C++, the linkage has nothing to do with scope, although scope (like linkage) is also tightly concerned with an identifier (in C) or a name (in C++) introduced by some declaration.
The linkage rule of namespace scope const variable is something special (and particularly different to the const object declared in file scope in C language which also has the concept of linkage of identifiers). Since ODR is enforced by C++, it is important to keep no more than one definition of the same variable or function occurred in the whole program except for inline functions. If there is no such special rule of const, a simplest declaration of const variable with initializers (e.g. = xxx) in a header or a source file (often a "header file") included by multiple translation units (or included by one translation unit more than once, though rarely) in a program will violate ODR, which makes to use const variable as replacement of some object-like macros impossible.
I think Internal and External Linkage in C++ gives a clear and concise explanation:
A translation unit refers to an implementation (.c/.cpp) file and all
header (.h/.hpp) files it includes. If an object or function inside
such a translation unit has internal linkage, then that specific
symbol is only visible to the linker within that translation unit. If
an object or function has external linkage, the linker can also see it
when processing other translation units. 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.
The compiler defaults the linkage of symbols such that:
Non-const global variables have external linkage by default
Const global variables have internal linkage by default
Functions have external linkage by default
Basically
extern linkage variable is visible in all files
internal linkage variable is visible in single file.
Explain: const variables internally link by default unless otherwise declared as extern
by default, global variable is external linkage
but, const global variable is internal linkage
extra, extern const global variable is external linkage
A pretty good material about linkage in C++
http://www.goldsborough.me/c/c++/linker/2016/03/30/19-34-25-internal_and_external_linkage_in_c++/
Linkage determines whether identifiers that have identical names refer to the same object, function, or other entity, even if those identifiers appear in different translation units. The linkage of an identifier depends on how it was declared.
There are three types of linkages:
Internal linkage : identifiers can only be seen within a translation unit.
External linkage : identifiers can be seen (and referred to) in other translation units.
No linkage : identifiers can only be seen in the scope in which they are defined.
Linkage does not affect scoping
C++ only : You can also have linkage between C++ and non-C++ code fragments, which is called language linkage.
Source :IBM Program Linkage
In C++
Any variable at file scope and that is not nested inside a class or function, is visible throughout all translation units in a program. This is called external linkage because at link time the name is visible to the linker everywhere, external to that translation unit.
Global variables and ordinary functions have external linkage.
Static object or function name at file scope is local to translation unit. That is
called as Internal Linkage
Linkage refers only to elements that have addresses at link/load time; thus, class declarations and local variables have no linkage.