Why “unused attribute” generated warning for array of struct?

佐手、 提交于 2019-12-30 11:16:31

问题


Here used, unused attribute with structure.

According to GCC document:

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.

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;
}

Why does GCC generated warning for array of struct?


回答1:


You are not attaching the attribute to a variable, you are attaching it to a type. In this case, different rules apply:

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.

This is exactly what happens inside func1: variable struct St s is of type struct St, so the warning is not generated.

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.

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
}

Demo.




回答2:


This attribute should be applied on a variable not struct definition. Changing it to

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

will do the job.



来源:https://stackoverflow.com/questions/47053565/why-unused-attribute-generated-warning-for-array-of-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!