What is the difference between non-inline function linkage and inline function linkage?
There is none; see [dcl.inline] note 1
The inline
keyword has no effect on the linkage of a function.
However, inline
results in a relaxation of the one-definition-rule (ODR):
For any definable item D
with definitions in multiple translation units,
- if
D
is a non-inline non-templated function or variable, or
- if the definitions in different translation units do not satisfy the following requirements,
the program is ill-formed; [...]
- [basic.def.odr] p14
In other words, it is possible for an inline function to be defined in multiple translation units (i.e. .cpp
files) without getting a linker error.
This works because the linker chooses one definition and ignores all others.
In other words, an inline function is a weak symbol.
However, [basic.def.odr] defines heavy restrictions.
Namely, an inline function needs to be defined exactly the same, token by token, everywhere.
For example:
// a.cpp
inline int foo() { return 0; }
// b.cpp
inline long foo() { return 0; }
Such a program is ill-formed, no diagnostic required because the definitions are not identical.
The easiest way to ensure that all definitions are identical is by putting them in a header.
Headers are copied and pasted into translation units with #include
, making it much less likely that you've messed up. See also Why do inline functions have to be defined in a header file?
What about "inlining"?
The compiler will inline functions as an optimization regardless whether inline
was used or not.
As long as a definition of the function is visible to the compiler, it will perform this optimization.
inline
merely provides a hint which contributes to the heuristic which decides whether inlining should take place.
See also: Are the "inline" keyword and "inlining" optimization separate concepts?