If a header file contains a function definition it can be inlined by the compiler. If the function is exported, the function’s name and implementation must also be made available to clients during linkage. How does a compiler achieve this? Does it both inline the function and provide an implementation for external callers?
Consider Foo.h:
class Foo
{
int bar() { return 1; }
};
Foo::bar may be inlined or not in library foo.so. If another piece of code includes Foo.h does it always create its own copy of Foo::bar, whether inlined or not?
Header files are just copy-pasted into the source file — that’s all
#includedoes. A function is onlyinlineif declared using that keyword or if defined inside the class definition, andinlineis only a hint; it doesn’t force the compiler to produce different code or prohibit you from doing anything you could otherwise do.You can still take the address of an
inlinefunction, or equivalently, as you mention, export it. For those uses, the compiler simply treats it as non-inlineand uses a One Definition Rule (the rule which says the user can’t apply two definitions to the same function, class, etc) to “ensure” the function is defined once and only one copy is exported. Normally you are only allowed to have one definition among all sources; an inline function must have one definition which is repeated exactly in each source it is used.Here is what the standard has to say about
inline externfunctions (7.1.2/4):