Must the definition of a C++ inline functions be in the same file?

It's imperative that the function's definition (the part between the {...}) be placed in a header file, unless the function is used only in a single .cpp file.
In particular, if you put the inline function's definition into a .cpp file and you call it from some other .cpp file, you'll get an "unresolved external" error from the linker.

[read more]


Normally the entire inline functions lives in the .h The reason is the compiler has to see the entire inline definition up front. Inline functions are compiled by directly 'pasting' the emitted machine language.


We usually put the inline function in the header file, so the compiler can see the definition while compiling the code that uses the function. That way it works with all compilers.

Some compilers have features for optimizing the whole program at once (Whole program optimization or Link time optimization). These compilers can inline a function even if it is defined in a different .cpp file.