Home » Home » Translation units and linkage OF C++


In the C++ programming language, translation units and linkage are crucial ideas that specify how various parts of code are compiled and linked to create a full programme. We will go into great detail about these ideas in this article.

The individual chunks of source code that the compiler compiles are known as translation units. Each translation unit has the option of containing one or more classes, variables, and functions. Each translation unit receives its own object file from the compiler. The object file extension in C++ is typically.obj or.o. A single executable file is then produced by the linker by combining all the object files.


The rules that govern how symbols defined in various translation units are linked together are referred to as linkage. A variable, function, or class with a name is referred to as a symbol. In C++, there are three distinct linking types.

External linkage:

Externally linked symbols are visible to other translation units. The extern keyword can be used to access them from other files. External linking is the default for functions and variables declared outside of any function or class.

Internal linkage:

Internally linked symbols can only be seen within the translation unit in which they are defined. Internal linking is the default for variables and functions declared inside a namespace.

No linkage:

Symbols that are not linked to anything else can only be seen in the block in which they are defined. A function’s internal variables are unlinked.

To understand linkage, let’s consider an example:

// file1.cpp int global_var = 10;

// file2.cpp extern int global_var; void func() { std::cout << global_var << std::endl; }

File1.cpp in this illustration defines a global variable called global var. Since the variable is defined outside of any function or class, it has external linkage. The identical variable is declared in File2.cpp using the extern keyword, signifying external linkage. Furthermore specified in file2.cpp, the function func() makes use of the global variable.


The linker will combine the object files and resolve the external reference to global var by linking it to the definition in file1.cpp when we compile and link these two files. As a result, the function func() will output the value 10 for global var.


In conclusion, it’s crucial to comprehend translation units and linkage while creating complex C++ applications. You may write effective, maintainable code that is simple to compile and link by appropriately structuring your code into translation units and controlling linkage.

Related Posts

Leave a Reply