当我们不能声明函数内联(GCC 编译器)时?

When we mustn't declare function inline(GCC compiler)?

本文关键字:编译器 GCC 不能 我们 声明 函数      更新时间:2023-10-16

我需要编写一个程序,以发现内联函数使用的限制。

我找到了GCC编译器的以下信息(http://gcc.gnu.org/onlinedocs/gcc/inline.html#inline):

请注意,函数定义中的某些用法可能使其不适合内联替换。这些用法包括:variadic功能,使用同种使用,使用计算的goto(请参见标签作为值),使用非局部goto,使用嵌套功能,使用setJMP,使用__builtin_longjmp以及__builtin_longjmp的使用以及__builtintin_retin_retin_retin_retin_retin_retin_retin_retin_retin_retin_retin_retin_retin_retin_retin_retin_ertin_retinter或__builtintin_builtintin_apply_apply_apply_args。使用-Winline警告,当无法替换为内联函数并给出故障的原因。

然后我用variadic函数编写了以下程序:

#include <cstdarg>
#include <iostream>
using namespace std;
inline double average(int count, ...) {
    va_list ap;
    int j;
    double sum = 0;
    va_start(ap, count);
    for (j = 0; j < count; j++) {
        /* Increments ap to the next argument. */
        sum += va_arg(ap, int);
    }
    va_end(ap);
    return sum / count;
}  
int main(void) {
    cout << average(4,6,8,2,3);
    return 0;
}

然后像这样编译我的程序:g++ -Wall -Winline program.cpp。汇编后,-Winline没有警告。

我做错了什么?感谢您的回答!

您链接的页面:

GCC不优化

时不会内联任何功能

在命令行中添加-O2在Godbolt中产生以下警告:

<source>: In function 'double average(int, ...)':
<source>:6:15: warning: function 'double average(int, ...)' can never be inlined because it uses variable argument lists [-Winline]
 inline double average(int count, ...)   
               ^~~~~~~
<source>: In function 'int main()':
<source>:6:15: warning: inlining failed in call to 'double average(int, ...)': function not inlinable [-Winline]
<source>:23:30: note: called from here
     cout << average(4,6,8,2,3);
                              ^