Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do inline functions have external linkage by default?

The standard says that given a declaration of

inline void foo();

that foo is an inline function with external linkage (because by default all function declarations have external linkage). This strikes me as odd. because the one definition rule section 3.2 (in both C++03 and C++11) say:

3 ... An inline function shall be defined in every translation unit in which it is used.

5 There can be more than one definition of a[n] ... inline function with external linkage (7.1.2) ... Given such an entity named D defined in more than one translation unit ... each definition of D shall consist of the same sequence of tokens

This means that an inline function might as well have internal linkage, because use of the function in any way through external linkage (that is, across translation units) would be to invoke undefined behavior (by paragraph 3), and that the content of the inline function in all translation units needs to be the same.

Is there a backwards compatability or specific toolchain reason for this rule?

like image 816
Billy ONeal Avatar asked Feb 16 '12 04:02

Billy ONeal


People also ask

What is the default linkage of a global function?

by default, global variable is external linkage. but, const global variable is internal linkage.

Why do you use inline functions and explain it with default arguments?

Inline Functions in C++ Inline functions are used to reduce the function call. When one function is being called multiply times in the program it increases the execution time, so inline function is used to reduce time and increase program efficiency.

Can inline functions extern?

An extern inline function is declared by a file scope declaration with the extern storage-class-specifier (that is, the function definition and/or prototype). For an extern inline function the compiler will provide a global definition of the function in the resulting object file.

What is external linkage?

The term external linkage means that a symbol in one translation unit can be accessed from other translation units, whereas exporting refers to a symbol that is visible from a library file such as a DLL. Only external linkage symbols can be exported.


1 Answers

One result of that decision is that a static variable defined within an inline function will be shared between all instantiations of the function. If the default had been internal linkage, each translation unit would have gotten its own copy of the static variable. That's not how people expect things to work - inline vs. non-inline shouldn't affect the code semantics so drastically.

like image 185
Mark Ransom Avatar answered Sep 25 '22 01:09

Mark Ransom