我已经搜索过,但无法验证当声明位于 .h 文件中且定义位于 .cpp 文件中时,GCC 编译器将如何处理内联 getter 和 setter。
大多数人似乎都说 GCC 无法跨越这些源文件障碍,并且根本无法内联它们,而其他人则不同意。我查看了文档,但也找不到答案。我错过了吗?
我确实意识到内联是编译器做出的选择,并不总是能保证,但假设最佳情况,它至少是可能的吗?
最佳答案
(您真正想问的是定义与您当前正在编译的文件位于不同的 .cpp
文件中,然后稍后链接的情况。编译器不会'不关心 .hpp
或 .cpp
,而是关心 translation units 。)
无论如何,关于http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html ,向下滚动到“flno”:
This option runs the standard link-time optimizer. [...] The first two invocations to GCC will save a bytecode representation of GIMPLE into special ELF sections inside foo.o and bar.o. The final invocation will read the GIMPLE bytecode from foo.o and bar.o, merge the two files into a single internal image, and compile the result as usual. Since both foo.o and bar.o are merged into a single image, this causes all the inter-procedural analyses and optimizations in GCC to work across the two files as if they were a single one. This means, for example, that the inliner will be able to inline functions in bar.o into functions in foo.o and vice-versa.
所以,是的,跨模块边界优化内联是可能的。
但是,C++ 仍然提出以下要求:
An inline function shall be defined in every translation unit in which it is used. [3.2/3, C++03]
因此,事实上,如果您使用 inline
关键字,您可能不会编写代码来利用这一点;相反,您依赖于链接器“只是决定”在认为合适的情况下内联您的函数。因此,这不是一个允许您移动代码的选项。
请记住,在代码中编写内联
与实际内联的函数并不具有一对一的关系;这只是对编译器(或链接器,如果您打开了上述链接时优化)的提示。
关于c++ - 当.h和.cpp文件中的定义和声明分开时,getter和setter可以内联吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5234978/