External Linkage V.S Internal Linkage

 
Compilation Units

A compilation unit is C/C++ source code that is compiled and treated as one logical unit. When C/C++ files is compiling, the preprocessor will include the header file recursively. Next the compilation unit will be compiled to object file(.o or .obj). Programs composed of more than one compilation unit can be separately compiled, and later linked to produce the executable program.

Internal Linkage

If a signature is local in its compilation unit, and it can't confilict with the same signature in other compilation units at link phase. We call this signature has internal linkage.

External Linkage

If  a signature will be used to search by other compilation units. We call this signature has external linkage. In other words, if we define this signature in different compilation unit, the compiler will give us an error like: multiple name.

First, I must say all declaration in C++ is neither Internal linkage nor External Linkage, we called it No Linkage. Next I summarized some items to recognise whether a signature is external linkage or not:
1. In a class, the signature of member method defination, the signature of static member method defination and the signature of static member var defination has external linkage.
2. In a namespace(include global namespace), the signature of non-static function defination, the signature of non-static friend function defination and the signature of non-static variable defination  has external linkage.
We can use an example to prove it:
// A.h
class A
{
public:
        int foo();
}
// AA.cpp
#include “A.h“
int A::foo()
{
        return 0; 
}
//AAA.cpp
#include “A.h“
int A::foo()
{
        return 1; 
}
If you compile this code,  you will get the“A::foo already defined in TestEnum.obj“ link error. Because the signature of member function defination has external linkage.If we modify the AAA.cpp file to:
// AAA.cpp
// no code, only include AAA.h
#include “A.h“
There is no error. We can see the signature of class defination has internal linkage.

 I think other case is internal linkage except items that I summarized above, like  the signature of class defination, the signature of union/enum defination etc. If you are a chariness person, you must find all signature with external linkage which can not be located in header file, only in cpp file. Reversely, all signature with internal linkage can be located in header file.

你可能感兴趣的:(External Linkage V.S Internal Linkage)