【问题标题】:Difference between gcc __attribute__ placementgcc __attribute__ 位置之间的区别
【发布时间】:2018-12-03 09:06:10
【问题描述】:

在使用 gcc __attribute__ 处理函数时,我注意到代码生成会有所不同,具体取决于我放置属性的位置。 在下面的示例中,我希望编译器不要优化我对 use() 的调用。

编译器:x86-64 gcc(trunk)

选项:-O3 -Wall

void  __attribute__((noinline, optimize("O0"))) use() {} 
int main () 
{
    use();
}
use:
        push    rbp
        mov     rbp, rsp
        nop
        pop     rbp
        ret
main:
        xor     eax, eax
        call    use
        xor     eax, eax
        ret

但是,如果我更改属性的位置,则会生成不同的代码。

void   use() {} __attribute__((noinline, optimize("O0")))
int main () 
{
    use();
}
main:
        push    rbp
        mov     rbp, rsp
        mov     eax, 0
        pop     rbp
        ret
use:
        ret

如果我不放任何属性,我会得到这个:

void   use() {} 
int main () 
{
    use();
}
use:
        ret
main:
        xor     eax, eax
        ret

现在,我在gcc_Common-Function-Attributes 看到的属性都存在于函数声明中,而不是定义中。我不确定我是否应该只在声明中使用它们。(因为在定义中使用它们似乎在上面的一个实例中有效) 我的问题是放置 __attribute__ 的规则是什么,为什么上述行为会这样? 我查了gcc_Attribute-Syntax,但恐怕我不是很了解。

【问题讨论】:

    标签: c gcc gcc-extensions


    【解决方案1】:

    __attribute__ 是它后面的函数规范的一部分。你的第二个版本实际上是:

    __attribute__((noinline, optimize("O0"))) int main() {
        ...
    }
    

    您正在设置main() 函数的属性,而不是use() 函数。

    请记住,newlies 在解析 C 代码时没有任何特殊含义,因此将属性与 use() 声明放在同一行实际上并不能使其成为其中的一部分。

    【讨论】:

    • specification of the function that follows it - 但void func __attribute__((..))) 也可以。我认为它更像constconst 总是适用于左边最近的类型标识符,除非没有,在这种情况下它适用于右边的那个。您不能将属性放在} 之后,因为这就像将const 放在分号或等号之后。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2013-11-10
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    相关资源
    最近更新 更多