现代 C++ 编译器可以内联 cpp 文件中定义的函数吗

2022-01-17 00:00:00 inline compiler-construction c++

我知道关键字 inline 具有有用的属性,例如用于将模板特化保存在头文件中.另一方面,我经常读到 inline 作为编译器实际内联函数的提示几乎毫无用处.此外,该关键字不能在 cpp 文件中使用,因为编译器希望在调用时检查标有 inline 关键字的函数.

I am aware that the keyword inline has useful properties e.g. for keeping template specializations inside a header file. On the other hand I have often read that inline is almost useless as hint for the compiler to actually inline functions. Further the keyword cannot be used inside a cpp file since the compiler wants to inspect functions marked with the inline keyword whenever they are called.

因此,我对现代编译器(即 gcc 4.43)的自动"内联功能有点困惑.当我在 cpp 中定义一个函数时,如果编译器认为内联对函数有意义,或者我是否剥夺了他的一些优化能力,编译器是否可以内联它?(这对于大多数函数来说都很好,但对于经常调用的小函数来说很重要)

Hence I am a little confused about the "automatic" inlining capabilities of modern compilers (namely gcc 4.43). When I define a function inside a cpp, can the compiler inline it anyway if it deems that inlining makes sense for the function or do I rob him of some optimization capabilities ? (Which would be fine for the majority of functions, but important to know for small ones called very often)

推荐答案

这取决于你的编译标志.使用 -combine-fwhole-programgcc 将跨 cpp 边界进行函数内联.如果你编译成多个目标文件,我不确定链接器会做多少.

This depends on your compilation flags. With -combine and -fwhole-program, gcc will do function inlining across cpp boundaries. I'm not sure how much the linker will do if you compile into multiple object files.

相关文章