这里使用,未使用
结构的属性。
根据 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 astruct
), 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
,而是的数组>结构圣
。此数组类型没有附加特殊属性,因此会生成警告。
您可以使用 typedef
将属性添加到特定大小的数组类型:
typedef __attribute__ ((unused)) struct St ArrayOneSt[1];
...
void func2() {
ArrayOneSt s; // No warning
}
关于c - 为什么 "unused attribute"为结构数组生成警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47053565/