为什么 "unused attribute" 为结构数组生成警告?

Why "unused attribute" generated warning for array of struct?

这里使用了,unused具有结构的属性。

根据 GCC 文件:

unused :

This attribute, attached to a variable, means that the variable is meant to be possibly unused. GCC will not produce a warning for this variable.

但是,在下面的代码中,结构数组产生了警告。

#include <stdio.h>

struct __attribute__ ((unused)) St 
{ 
    int x; 
};

void func1()
{
  struct St s;      // no warning, ok
}

void func2()
{ 
  struct St s[1];   // Why warning???
}

int main() {
    func1();
    func2();
    return 0;
}

为什么 GCC 对结构数组生成警告?

您不是将属性附加到变量,而是将其附加到类型。在这种情况下,适用不同的规则:

When attached to a type (including a union or a struct), this [unused] attribute means that variables of that type are meant to appear possibly unused. GCC will not produce a warning for any variables of that type, even if the variable appears to do nothing.

这正是 func1 内部发生的情况:变量 struct St s 的类型为 struct St,因此不会生成警告。

但是func2就不一样了,因为St s[1]的类型不是struct St,而是struct St的数组。此数组类型没有附加特殊属性,因此会生成警告。

您可以使用 typedef 将属性添加到特定大小的数组类型:

typedef __attribute__ ((unused)) struct St ArrayOneSt[1];
...
void func2() { 
  ArrayOneSt s;   // No warning
}

Demo.

此属性应应用于变量 而不是 struct 定义。 将其更改为

void func2()
{ 
  __attribute__ ((unused)) struct St s[1];  
}

会完成任务的。