c++ltoinlining

No need to define functions in header files for inlining?


In order for the compiler to inline a function call, it needs to have the full definition. If the function is not defined in the header file, the compiler only has the declaration and cannot inline the function even if it wanted to.

Therefore, I usually define short functions that I imagine the compiler might want to inline in header files.

With the whole-program optimization (/LTCG and /GL), is there no longer need for defining functions in header files to allow them to be inlined?

Are there other reasons to define functions in header files, except in some cases with templates?


Solution

  • One reason is because you want to distribute single-header libraries, like STB. Also, linking is notoriously slow, even with new linkers like gold and LLD. So, you might want to avoid linking, and instead include everything in a single file.

    This can go beyond linking and just function definitions. The idea is to generally include everything only once to reduce compile-time, because the C++ compilation model is quite bad and slow, and part of the reason is that things are re-compiled. This is the idea of the unity build.

    If you think that a unity build sounds super dumb, consider that Ubisoft (at least used to) use it.