Must the definition of a C++ inline functions be in the same file?
Solution 1
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.
Solution 2
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.
Solution 3
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.
![AlexDan](https://i.stack.imgur.com/eSiYW.jpg?s=256&g=1)
AlexDan
I want to know : "WHY" & "WHEN" Instead of : "HOW" & "WHAT" .
Updated on June 05, 2022Comments
-
AlexDan about 2 years
I defined a function
show()
as inlined in a header file calledex.h
and the definition of the function insideex.cpp
. I expected that this will give me an error since the compiler will not know what to replace where theshow()
function is called. But because I'm using an IDE, it worked fine. How could this happen?And BTW when I tried to compile it manually it gave me an error that the
show()
is used but not defined.