I defined a function show()
as inlined in a header file called ex.h
and the definition of the function inside ex.cpp
. I expected that this will give me an error since the compiler will not know what to replace where the show()
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.
It is not possible to link to an inline function in another file. In particular, extern functions are not inlined. Because __inline has C++ semantics, declaring a function as __inline means that it cannot be called from another compilation unit.
An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit.
An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. This eliminates call-linkage overhead and can expose significant optimization opportunities.
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]
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With