简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM