Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is external linkage and internal linkage?

Tags:

c++

c++-faq

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.

like image 782
rkb Avatar asked Aug 31 '09 17:08

rkb


People also ask

Is a linker internal or external?

The linker goes through the compiled code and finds x and z first. As they are global variables, they are externally linked by default.

How many types of linkages are there in C++?

Explanation: There are three types of linkage in c++. They are an internal linkage, external linkage, and no linkage.

What is mean by linkage in C?

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.


2 Answers

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).

like image 79
dudewat Avatar answered Oct 10 '22 08:10

dudewat


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 } 
like image 35
Motti Avatar answered Oct 10 '22 07:10

Motti