【问题标题】:GCC attributes influence on nested functionsGCC 属性对嵌套函数的影响
【发布时间】:2014-03-12 10:14:11
【问题描述】:

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

//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,解析父函数引用、外部标签跳转等。在下一阶段,嵌套函数将转换为具有内联能力的独立函数。但目前还不清楚父函数的属性。他们申请嵌套了吗?

【问题讨论】:

  • 你真的试过了吗?它似乎对我有用。您使用的是什么版本的 gcc 以及哪些命令行开关?
  • @PaulR gcc version 4.8.1 20130909 [gcc-4_8-branch revision 202388] 编译为:gcc -std=gnu99 -O2 file.c
  • 当然可以编译——它是正确的 C 代码(但逻辑上不正确——hot_nested_function 声明为全局,而不是嵌套)。
  • 嵌套函数在 C 中已被弃用,已经有一段时间了。如果发现支持处于某种比特腐烂状态,我不会太惊讶。
  • 我认为您的 gcc 命令行中缺少 -fnested-functions

标签: c gcc compiler-construction c99 function-attributes


【解决方案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();
}

至于自动应用于所有包含对象的属性-我不知道,文档对此没有任何说明,因此由编译器决定。最好手动指定 - 编译器版本之间的行为可能会有所不同。

【讨论】:

  • 请添加解释,以便其他有相同问题或出于学习目的阅读的人可以理解更改。谢谢。
  • 谢谢,可能我错过了这部分文档。但是问题的第二部分呢? 'some_function' 的 __ 属性 __ 是否对嵌套函数有任何影响?
  • @AlexanderSannikov 对不起,不知道。但是,用更多信息更新了答案。它可以通过反汇编来测试——但同样,在不同的 gcc 版本中会发生什么。
  • @keltar,无论如何,非常感谢。我会尝试拆解不同的版本。
猜你喜欢
  • 1970-01-01
  • 2017-04-26
  • 2019-09-29
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2011-12-18
  • 2022-11-13
  • 2018-06-03
相关资源
最近更新 更多