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

前端 未结 2 1472
挽巷
挽巷 2021-01-14 23:40

Here used, unused attribute with structure.

According to GCC document:

unused :

This attribute, atta

相关标签:
2条回答
  • 2021-01-14 23:48

    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.

    0 讨论(0)
  • 2021-01-14 23:58

    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.

    0 讨论(0)
提交回复
热议问题