Linkages, Extern, and Inline

Linkage describes the visibility of variable and function names across translation units. Extern and inline are ways to manipulate that visibility.

There are three types of linkage, no-linkage, internal and external. A function local variable is said to have no-linkage as it’s only accessible in the function. Const variables have internal linkage, which means they are accessible from the same translation unit. Non const global  variables and functions have external linkage, which means they are accessible in the same and other translation units.

Extern and inline, along with static and anonymous namespaces, allow you to flip the linkage of a variable of function. Consider the following code:

main.cpp:

extern const some_var {10};

some-other.cpp

extern const some_var;

makes the some_var in some-other.cpp the same one as in main.cpp. Normal variables can also be declared extern. And:

main.cpp:

inline int add(int a, int b) {
    return a + b;
}

some-other.cpp:

inline int add(int a, int b) {
    return a + b;
}

will be optimised to a single function, thus not breaking the single definition rule. The functions must be exactly the same. Variables can also be declared inline.

 

Variables and functions can be declared static or put in an anonymous namespace to make them local to the translation unit. Static is considered old fashioned and in modern C++, namespaces should be used.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.