Inline keyword vs header definition

SirYakalot picture SirYakalot · Apr 11, 2012 · Viewed 11.1k times · Source

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; }

Answer

Matthieu M. picture Matthieu M. · Apr 11, 2012

There are several facets:

Language

  • When a function is marked with the inline keyword, then its definition should be available in the TU or the program is ill-formed.
  • Any function defined right in the class definition is implicitly marked inline.
  • A function marked inline (implicitly or explicitly) may be defined in several TUs (respecting the ODR), whereas it is not the case for regular functions.
  • Template functions (not fully specialized) get the same treatment as inline ones.

Compiler behavior

  • A function marked 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).
  • Whereas the compiler actually inlines the call (ie, copy/paste the code at the point of use instead of performing a regular function call) is entirely at the compiler's discretion. The presence of the keyword may, or not, influence the decision but it is, at best, a hint.

Linker behavior

  • Weak symbols are merged together to have a single occurrence in the final library. A good linker could check that the multiple definitions concur but this is not required.