【问题标题】:When we mustn't declare function inline(GCC compiler)?什么时候我们不能声明函数内联(GCC 编译器)?
【发布时间】:2019-03-02 13:31:56
【问题描述】:

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

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

请注意,函数定义中的某些用法可能使其不适合内联替换。这些用法包​​括:可变参数函数、alloca 的使用、计算的 goto 的使用(参见作为值的标签)、非本地 goto 的使用、嵌套函数的使用、setjmp 的使用、__builtin_longjmp 的使用以及 __builtin_return 或 __builtin_apply_args 的使用。当标记为 inline 的函数无法替换时,使用 -Winline 会发出警告,并给出失败的原因。

然后我用可变参数编写了以下程序:

#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 的警告。

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

【问题讨论】:

    标签: c++ gcc


    【解决方案1】:

    从您链接的页面:

    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);
    
                                  ^
    

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 2011-01-25
      • 1970-01-01
      • 2010-12-28
      • 1970-01-01
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      相关资源
      最近更新 更多