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

标签 c arrays gcc struct unused-variables

这里使用,未使用结构的属性。

根据 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,而是的数组>结构圣。此数组类型没有附加特殊属性,因此会生成警告。

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

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

Demo.

关于c - 为什么 "unused attribute"为结构数组生成警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47053565/

相关文章:

c - 为什么 ls -al 不显示 mq_open 创建的消息队列

javascript - 为什么每次点击时数组都是空的?

java - 使用ASM访问数组

C memcpy 在 Linux 和 Windows 上的行为不同

c - 将指针插入 GCC 中的 eax 和 ebx 寄存器

c++ - C4244 复合加法赋值的 4 级警告,但不是求和和赋值

c - 协议(protocol)不支持地址族 UDP C 错误发送

c++ - gcc内联汇编jmp地址;裸函数

c - 在C中处理完数组的最后一行后,while循环卡住了

c# - 如何将播放器存储在阵列中?