3

When one function calls another, and inlining is desired, is the order of the definitions of the two functions important? Assume that the two definitions occur in the same translation unit.

I am primarily interested in what the C++ standard says about it, if anything. However, if you have important information about the inlining behavior in specific compilers, I would be interested in that too. Please assume that no link-time optimization occurs (is disabled).

Specifically, are the following two versions equally likely to achieve inlining according to the C++ standard?

Version one:

inline void foo() { ... }
void bar() { ... foo(); ... }

Version two:

inline void foo();
void bar() { ... foo(); ... }
void foo() { ... }

EDIT: Please note that this question is not about the effectiveness of the inline keyword with respect to achieving inlining in general. I specifically ask about whether the standard says anything about the order of function definitions in relation to achieving inlining.

4

2 回答 2

4

C++ 标准在这里没有任何强制要求。编译器可以在他们认为合适的任何情况下自由内联或不内联。除了允许同一函数的多个定义外, inline 关键字可能没有任何作用。

大多数编译器将能够内联翻译单元可用的任何函数,无论它在源代码中出现的顺序如何。前向声明通常只影响源文件中给定点可用的名称,而不影响二进制文件的最终输出。

于 2013-07-15T21:00:20.280 回答
3

实际上,inline关键字与内联代码的关系不大,而与允许legal violation一个定义规则有关。内联的主要目的是告诉编译器一个函数可能出现在多个翻译单元中(并且在每个翻译单元中都有相同的定义)。这允许它在链接阶段避免多个定义错误。

使用inline关键字并不能保证编译器会内联函数——这只是一个建议。此外,如果可以在翻译单元中看到定义并且编译器认为值得,许多编译器将内联未标记为内联的函数。我强烈怀疑您显示的任何一个版本都会被特定编译器内联或不被内联。

简而言之,让编译器决定是否内联,并以最易读的方式编写代码。

于 2013-07-15T21:13:14.940 回答