4

Unlike some people still believe, the inline keyword in C++ does not primarily exist to tell the compiler to inline-expand a function. It exists to tell the linker that there may be multiple definitions of a function and the user promises that all definitions are the same.

But it is also related to optimization. People usually say that it is a hint to the compiler to inline a function. I remember I once looked up the inlining metrics in the LLVM source code, and I think it rates a functions inline-value (as in performance gain if the function is inline-expanded) higher if it's declared with the inline keyword. Unfortunately I can't find it right now.

Nevertheless I think this is a strange behaviour. The one definition rule and the inline expansion optimization seem totally unrelated to each other. Why is there one keyword that controls both them both (at least to a degree)?

If the compiler knows best when to inline a function, why even take the hint from the inline keyword? Is it for historical reasons or does it have any practical value with modern compilers?

chrysante
  • 2,328
  • 4
  • 24
  • 3
    First mentioned purpose (*there may be multiple definitions of a function*) is the way to provide an opportunity for second purpose (*hint to the compiler to inline a function*). You can define inline function in header and include it to multiple compilation units. – dimich Aug 03 '23 at 11:49
  • 2
    Have you already read https://stackoverflow.com/a/27043088/4944425 ? The second paragraph seems related to your first question. – Bob__ Aug 03 '23 at 11:50
  • @Bob__ Yes, I know the function body needs to be visible during compilation. But the same applies to a `static` function or even an `extern` function that's defined in the same translation unit as one of its callsites. I guess arguably the primary reason to define (non-template) functions in headers is that you want them to be inlined. But another reason could be, that you don't want to require seperate compilation and linking for the one non-template function in your library of templates. Maybe in the end I'm just a bit orthodoxical about leaving low-level optimizations to the compiler. – chrysante Aug 03 '23 at 12:07
  • 3
    Historically, C (and later C++) has always had a separate compilation model so, and `inline` was originally about "inline-expand" which meant (almost) always a need to define such functions in every compilation unit that called it (e.g. in a header). `inline` was also a hint about "inline-expand" early on because even early compiler/optimisers often did better at deciding that than programmers. Wording of more recent standards have then evolved to emphasise the use of `inline` with multiple definitions and to deemphasise the "inline-expand" aspect. – Peter Aug 03 '23 at 13:53
  • @Peter: And then even more recent standards have moved back somewhat because of modules. – Davis Herring Aug 03 '23 at 19:59

0 Answers0