What's the difference between using the inline keyword before a function and just declaring the whole function in the header?
so...
int whatever() { return 4; }
vs
.h:
inline int whatever();
.cpp:
inline int myClass::whatever() { return 4; }
for that matter, what does this do:
inline int whatever() { return 4; }
The definition of an inline function doesn't have to be in a header file but, because of the one definition rule (ODR) for inline functions, an identical definition for the function must exist in every translation unit that uses it. The easiest way to achieve this is by putting the definition in a header file.
Answer. An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.
With inline keyword, the compiler replaces the function call statement with the function code itself (process called expansion) and then compiles the entire code.
There are several facets:
Language
inline
keyword, then its definition should be available in the TU or the program is ill-formed.inline
.inline
(implicitly or explicitly) may be defined in several TUs (respecting the ODR), whereas it is not the case for regular functions.inline
ones.Compiler behavior
inline
will be emitted as a weak symbol in each object file where it is necessary, this may increase their size (look up template bloat).Linker behavior
without inline
, you will likely end up with multiple exported symbols, if the function is declared at the namespace or global scope (results in linker errors).
however, for a class (as seen in your example), most compilers implicitly declare the method as inline (-fno-default-inline
will disable that default on GCC).
if you declare a function as inline, the compiler may expect to see its definition in the translation. therefore, you should reserve it for the times the definition is visible.
at a higher level: a definition in the class declaration is frequently visible to more translations. this can result in better optimization, and it can result in increased compile times.
unless hand optimization and fast compiles are both important, it's unusual to use the keyword in a class declaration these days.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With