2

C++ allows you to annotate functions with the inline keyword. From what I understand, this provides a hint (but no obligation) to the compiler to inline the function, thereby avoiding the small function calling overhead.

I have some methods which are called so often that they really should be inlined. But inline-annotated functions need to be implemented in the header, so this makes the code less well-arranged. Also, I think that inlining is a compiler optimization that should happen transparently to the programmer where it makes sense.

So, do I have to annotate my functions with inline for inlining to happen, or does GCC figure this out without the annotation when I compile with -O3 or other appropriate optimization flags?

4

2 回答 2

3

inline只是对编译器的建议是不正确的并且具有误导性。将函数标记为内联有两种可能的影响:

  1. 将函数定义内联替换到进行函数调用的位置 &
  2. 某些放宽 wrt一个定义规则,允许您在头文件中定义函数。

编译器可能会执行也可能不会执行#1,但它必须遵守#2. 所以内联不仅仅是一个建议。一旦函数被标记为内联,就会应用一些规则。

作为一般准则,不要inline仅仅为了优化而标记您的函数。大多数现代编译器将在没有您帮助的情况下自行执行这些优化。inline如果您希望将它们包含在头文件中,请标记您的函数,因为这是在不破坏 ODR 的情况下在头文件中包含函数定义的唯一正确方法。

于 2013-02-05T15:41:30.787 回答
1

常见的民间传说是 gcc 总是自行决定(基于一些成本启发式)是否内联某些东西(取决于编译器/链接器选项,它甚至可以在链接时这样做)。您有时可以在使用 -Winline 时观察到这一点,其中 gcc 警告内联提示已被忽略,它通常甚至给出一个原因。

如果您想确切地知道发生了什么,您可能必须阅读它的源代码,或者听读它的人的话。

于 2013-02-05T15:37:40.247 回答