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

▼魔方 西西 提交于 2019-12-04 17:25:58

问题


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.


回答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.

[read more]




回答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.




回答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.



来源:https://stackoverflow.com/questions/9338152/must-the-definition-of-a-c-inline-functions-be-in-the-same-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!