C++ External and Internal Linkage

| 分类 C++  | 标签 C++_keywords 

In a C++ program, there is an important rule called “One Definition Rule” (ODR). You can get more information about ODR with this reference

A program consists of one or more translation units. A translation unit consists of an implementation file and all the headers that it includes directly or indirectly. Implementation files typically have a file extension of .cpp or .cxx. Header files typically have an extension of .h or .hpp. Each translation unit is compiled independently by the compiler. After the compilation is complete, the linker merges the compiled translation units into a single program. Violations of the ODR rule typically show up as linker errors. Linker errors occur when the same name has two different definitions in different translation units.

A free function is a function that is defined at global or namespace scope. Non-const global variables and free functions by default have external linkage; they’re visible from any translation unit in the program. Variables declared within class definitions or function bodies have no linkage.

You can force a global name to have internal linkage by explicitly declaring it as static. This keyword limits its visibility to the same translation unit in which it’s declared. In this context, static means something different than when applied to local variables.

The following objects have internal linkage by default:

  • const objects
  • constexpr objects
  • typedef objects
  • static objects in namespace scope

To give a const object external linkage, declare it as extern and assign it a value.

If you want to use an external value, you should external declare it first as the following code shouws:

//A.cpp
#include "A.h"
string name = "Joey";

//main.cpp
#include "A.h"
extern string name;
cout << name << endl; //This will print out "Joey"

Take care of the multiple definitions of the same variable name. It will cause the link error.


上一篇     下一篇