__attribute__说明符可以同时用于函数原型和函数定义吗?

Can an __attribute__ specifier be used with both the function prototype and the function definition?

本文关键字:函数 原型 定义 说明符 attribute 用于      更新时间:2023-10-16

我的问题直接与__attribute__((noreturn))有关,但更普遍的是也可能与其他人有关-例如__attribute__(noinline)。我已经查看了gcc手册和Keil编译器参考指南,以确定使用__attribute__函数的正确语法。我所看到的大致如下:

void function (void) __attribute__((noreturn));  //Prototype has __attribute__
void function (void)                             //Definition does not.
{
    while (1);
}

我还看到在函数定义之前使用的__attribute__如下所示:

__attribute__((noreturn)) void function (void)
{
    while (1);
}

然而,我还没有看到它与函数原型和函数定义一起使用的例子。我认为在两个位置都有__attribute__会导致更好的代码可读性;我可以通过查看函数原型或定义来知道是否应用了属性。结果将如下所示:

__attribute__((noreturn)) void function (void) ;  //Prototype has __attribute__
__attribute__((noreturn)) void function (void)    //Definition has __attribute__
{                                               //as well.
    while (1);
}

我已经使用前面提到的方法成功地用Keil armcc编译器编译了代码。有任何理由为什么我应该使用此方法与armcc或gcc?

这里是GCC 4.0文档的一个片段。

The keyword __attribute__ allows you to specify special attributes when making a
declaration.

注意这里说的是"声明"而不是"定义"。这篇Unix Wiz的老文章也有很多好的建议。它还要求在声明中使用属性。

正如Sean Perry所说,看起来GCC只指定可以与声明一起使用的特殊属性。

我在ARMCC文档中挖掘了更多,终于找到了我要找的东西:

您可以在声明、定义或两者中设置这些函数属性。

因此,对于ARMCC 我的使用__attribute__如OP中所示是安全的,但对于GCC来说并非如此。