0

只能为函数声明(而不是定义)指定函数属性。所以,我不能为嵌套函数指定属性。例如:

//invalid line. hot_nested_function is invisible outside "some_function"
void hot_nested_function() __attribute__ ((hot));

//valid attribute for declaration
int some_function() __attribute__ ((hot));

int some_function(){
    void hot_nested_function(){
         //time critical code
    }
    for( int i=0; i<REPEAT_MANY_TIMES;i++)
        hot_nested_function();
}

在这种情况下,“hot_nested_function”会被优化为“hot”吗?

UPD:在一个愚蠢的例子中,gcc(意味着gcc -O1和更高的优化级别)用它的主体替换函数调用,无论是有还是没有__attribute__ ((hot))(对于嵌套函数)。甚至没有任何关于嵌套函数的提醒。

UPD2:根据gcc.git/gcc/tree-nested.c解析父函数引用、外部标签跳转等。在下一阶段,嵌套函数将转换为具有内联能力的独立函数。但目前还不清楚父函数的属性。他们申请嵌套了吗?

4

1 回答 1

1
int some_function(){
    void __attribute__ ((hot)) hot_nested_function(){
         //time critical code
    }
    for( int i=0; i<REPEAT_MANY_TIMES;i++)
        hot_nested_function();
}

gcc 的函数属性语法是其中之一

__attribute__ ((...)) returntype functionname(...)
returntype __attribute__ ((...)) functionname(...)
returntype functionname(...) __attribute__ ((...))

最后一个只能用于原型,而不能用于前两个。

另一种方法是

int some_function(){
    auto void hot_nested_function() __attribute__ ((hot));

    void hot_nested_function(){
         //time critical code
    }

    for( int i=0; i<REPEAT_MANY_TIMES;i++)
        hot_nested_function();
}

至于自动应用于所有包含对象的属性 - 我不知道,文档对此只字未提,因此由编译器决定。最好手动指定 - 编译器版本之间的行为可能会发生变化。

于 2014-03-12T10:23:09.887 回答