What does 'inline' mean?

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Jun 12 13:22:35 UTC 2020


On 6/8/20 2:14 AM, Manu wrote:
> In C/C++, inline says that a function will be emit to the binary only 
> when it is called, and the function is marked with internal linkage (it 
> is not visible to the linker from the symbol table)

By my recollection this is not the case for C++, at all.

* "inline" does NOT change a function's linkage in C++. You may have 
inline functions with internal linkage (static inline) or (default) 
external linkage. This is important because e.g. defining a static 
variable in an extern inline function will have the same address in all 
calls to the function.

* "inline" in C++ is entirely advisory, meaning a conforming 
implementation is entirely free to simply ignore it, save it for 
duplicate symbols (which are ignored for inline functions and cause 
errors for non-inline functions).

* In fact, all major C++ implementations routinely ignore "inline" in 
favor of their own heuristics, which are usually better. However, they 
are not always better, and that in turn has generated demands for an "I 
really mean inline" directive. Compiler implementers responded to that 
demand with a trickle of additional nonstandard language features:

- MSVC has __inline, __forceinline, and __declspec(noinline): 
https://docs.microsoft.com/en-us/cpp/cpp/inline-functions-cpp?view=vs-2019. 
As a funny aside, __inline and __forceinline sometimes do not inline, 
and __declspec(noinline) functions are sometimes inlined.

- g++ and clang have __inline__, __attribute__((always_inline)), and 
__attribute__ ((noinline)): 
https://stackoverflow.com/questions/8381293/how-do-i-force-gcc-to-inline-a-function. 
Needless to say, __inline__ and __attribute__((always_inline)) do not 
always inline, and __attribute__ ((noinline)) does not always prevent 
inlining.

If the above is correct, a D language feature dedicated to inlining 
should do the following:

* Always emit the function body in the .di file if ever asked to 
generate it.

* Never complain about duplicate symbols if an inline function has 
duplicate definitions.

Then compilers can decide on specific inlining strategies using the 
language feature as a hint.

D does ALL of the above already for templates, so this is not a 
difficult feature to implement. In fact we use this technique (e.g. in 
druntime) by spelling inline as "()". Consider:

int func(int) { ... body ... }

Let's make this inline:

int func()(int) { ... body ... }

Done.

In D there's one additional implication of body availability - the 
function is eligible for CTFE. I think any adjustment to the extant 
inline pragma needs to make this a top-level consideration.


More information about the Digitalmars-d mailing list