What does 'inline' mean?
Johan
j at j.nl
Fri Jun 12 18:08:57 UTC 2020
On Friday, 12 June 2020 at 13:22:35 UTC, Andrei Alexandrescu
wrote:
> 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.
I believe Manu tried to explain that `inline` in C++ really only
affects how the linker must treat the symbol, and it is best to
remember that it does nothing at all concerning "inlining"
(putting function body inside another).
`inline` is really a misnomer.
The "linkage" effect of `inline` is required for C++ to work with
#include files. There is some room for confusion because,
depending on who is talking, the word "linkage" can have more
nuances than just internal/external. I personally take the broad
stance of "linkage" including anything the linker can do with the
symbol.
Without `inline`, you would get multiple definition linker errors
for functions defined in a header file when linking together two
translation units that both included that header file. Instead of
normal function linkage that forbids multiple definition,
`inline` changes linkage to merge multiple definitions into one.
In addition, emission of the function must happen in any
translation unit that references it (calling or address taken),
and thus that translation unit must also define it (in contrast
to just declaring it). I do not think `inline` forbids emission
if the function is not referenced.
Note that C++17 added `inline` for variables too, because without
it you run into the same problem of multiple definitions in e.g.
header-only libraries. Obviously that has nothing to do with
"inlining" the callee's body; it is purely a linker directive to
merge the symbols which is exactly the functionality it provides
for functions.
In D, this is actually not a problem: multiple definitions of
symbols are merged already. You'll never see a multiple
definition error with D (also not with extern(C) functions).
The wikipedia article seems fairly complete on all the
intricacies of `inline`:
https://en.wikipedia.org/wiki/Inline_function
And the cppreference text is also pretty clear
https://en.cppreference.com/w/cpp/language/inline .
-Johan
More information about the Digitalmars-d
mailing list