为什么要使用“未使用的属性"为结构数组生成警告? [英] Why "unused attribute" generated warning for array of struct?
问题描述
这里使用的是unused
具有结构的属性.
Here used, unused
attribute with structure.
根据 GCC 文件:>
未使用:
此属性附加到变量,表示该变量是 意味着可能未使用. GCC不会对此发出警告 变量.
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.
但是,在下面的代码中,结构数组生成了警告.
But, In the following code, array of struct generated warning.
#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会为结构体数组生成警告?
Why does GCC generated warning for array of struct?
推荐答案
您没有将属性附加到变量,而是将其附加到类型.在这种情况下,适用不同的规则:
You are not attaching the attribute to a variable, you are attaching it to a type. In this case, different rules apply:
当附加到类型(包括
union
或struct
)时,此[unused]属性表示该类型的变量可能看起来未使用.即使该变量似乎什么也不做,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
,因此不会生成警告.
This is exactly what happens inside func1
: variable struct St s
is of type struct St
, so the warning is not generated.
但是,func2
是不同的,因为St s[1]
的类型不是struct St
,而是struct St
的数组.此数组类型没有附加特殊属性,因此会生成警告.
However, func2
is different, because the type of St s[1]
is not struct St
, but an array of struct St
. This array type has no special attributes attached to it, hence the warning is generated.
您可以使用typedef
将属性添加到特定大小的数组类型:
You can add an attribute to an array type of a specific size with typedef
:
typedef __attribute__ ((unused)) struct St ArrayOneSt[1];
...
void func2() {
ArrayOneSt s; // No warning
}
这篇关于为什么要使用“未使用的属性"为结构数组生成警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!