5

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?

Evg
  • 25,259
  • 5
  • 41
  • 83
Magnar Myrtveit
  • 2,432
  • 3
  • 30
  • 51
  • 2
    Compilation/link times and memory usage can increase significantly with the above options for large / very large projects because of the the amount of work and memory needed to load and inspect all the meta-data for the whole project. – Richard Critten Apr 20 '22 at 07:41
  • When you say ***inline***, do you mean you defining it ***in-the-line,*** or do you mean using the **`inline`** specifier? – Ranoiaetep Apr 20 '22 at 07:45
  • 1
    The C++ developers will **never** agree on if it is better to prefer function definitions in header files or in cpp files. It is not about reason or need. It is religious question. – Öö Tiib Apr 20 '22 at 08:08
  • 1
    @RichardCritten There's certainly an impact, yes. My personal experience of LTO, let's call it, is that the Microsoft linker works very well when you enable this. It's still fast (it's fast anyway) and if you look at the resulting code, it appears to be effective. In particular, it aggressively inlines small functions defined in the body of other translation units. But the linker used by Apple clang on the Mac is a different story. I eventually gave up on it. Too slow and too many unwanted build products. So I would say, OP, if you want a function inlined, put it in a header file. – Paul Sanders Apr 20 '22 at 12:48
  • @Ranoiaetep I mean substituting the function call with the definition of the function. – Magnar Myrtveit Apr 22 '22 at 08:02

1 Answers1

1

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.