When do compilers inline C++ code?

The inline keyword really just tells the linker (or tells the compiler to tell the linker) that multiple identical definitions of the same function are not an error. You’ll need it if you want to define a function in a header, or you will get “multiple definition” errors from the linker, if the header is included in more than one compilation unit.

The rationale for choosing inline as the keyword seems to be that the only reason why one would want to define a (non-template) function in a header is so it could be inlined by the compiler. The compiler cannot inline a function call, unless it has the full definition. If the function is not defined in the header, the compiler only has the declaration and cannot inline the function even if it wanted to.

Nowadays, I’ve heard, it’s not only the compiler that optimizes the code, but the linker can do that as well. A linker could (if they don’t do it already) inline function calls even if the function wasn’t defined in the same compilation unit.

And it’s probably not a good idea to define functions larger than perhaps a single line in the header if at all (bad for compile time, and should the large function be inlined, it might lead to bloat and worse performance).

Leave a Comment