Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 878
AlexDan Avatar asked Feb 18 '12 03:02

AlexDan


People also ask

Can inline function be called from another file?

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.

Can we extern inline function and use it in other file?

An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit.

How do you define an inline function?

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.


3 Answers

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]

like image 189
kev Avatar answered Oct 07 '22 21:10

kev


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.

like image 22
Bo Persson Avatar answered Oct 07 '22 20:10

Bo Persson


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.

like image 4
seand Avatar answered Oct 07 '22 20:10

seand