c++ - 当.h和.cpp文件中的定义和声明分开时,getter和setter可以内联吗?

标签 c++ gcc inline

我已经搜索过,但无法验证当声明位于 .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/

相关文章:

c++ - 如何在win api中设置整个应用程序的字体?

c++ - 内联类函数和共享库 (dll) 构建

c++ - 我是否需要 .CPP 文件?仅使用 header 并使所有内容内联?

c - 强制静态函数内联有什么缺点吗?

c++ - 如何将#defines 从 C++ 共享库导出到应用程序

C++静态匿名类类型数据成员

gcc - gcc 4.5 中引入的关于链接的变化?

gcc - 如何使用 GCC 属性 'format' ?

c++ - 使用 C++ 标准库在 Linux 上编译

C++:字符串流到 vector