Why do inline functions have external linkage by d

2019-02-04 07:26发布

问题:

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?

回答1:

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.



回答2:

This is aptly answered here by Jonathan Schilling's article: Extern Inlines By Default.

To quote him about motivation for this change:

The immediate motivation for this change was a need of the new template compilation model that was adopted at the same meeting; but more generally it was felt that changing the default was an idea whose time had come, and the change was approved unanimously in both ANSI and ISO.