Why do inline functions have several identical definitions?

I am working on a C ++ Primer (5th Edition), and while this is really great stuff, I have found that in some cases I come across explanations that give me more questions than answers.

In the current example (highlighted in bold):

Unlike other functions, inline and constexpr functions can be defined several times in a program. In the end, to extend the code, the compiler needs a definition, not just a declaration. However, all definitions of a given inline or constexpr must match exactly . As a result, inline and constexpr functions are usually defined in headers.

I worked a bit on this and I saw many answers that I can define an inline function several times , as long as the definition is identical. In addition, I saw that the standard allows this. I'm curious: why?

Is there a possible encoding situation in which I will have #include for a given header file for the built-in function that I want, just to provide a duplicate definition in my .cpp file? I feel that I am missing an obvious situation where this rule applies. Why not just make it so that you can only define the built-in function once in the header, period and not worry about it later?

All the best.

+5
source share
2 answers

The answer is surprisingly simple: this is done so that you define the body of the built-in functions inside the header files.

Since the header files are “inserted” verbatim into the translation block that refers to them, any function definitions within the headers fall inside this translation unit. If you include the same header from several files, all of these files would have to define the same function with identical definitions (because they belong to the same header).

Since the preprocessing step is performed before compilation, the compiler has no idea which part of the translation unit comes from the header and which was in your cpp file. This is why it was easier for standard authors to allow multiple identical definitions.

+4
source

Why not just make it so that you can only define the built-in function once in the header, period and not worry about it later?

The reasons I can think of.

  • The compiler cannot ensure its execution. The content that it processes has already been pre-processed.

  • In addition, specifying that built-in functions will be defined only in header files is too strict. You will find a large number of classes defined only in the source files in real applications. It would be a shame if these classes could not use the inline functions.

+1
source

All Articles