首页 > 解决方案 > 静态结构警告空声明中无用的存储类说明符

问题描述

  static struct astr {
          int a;
  };

  static const struct astr newastr = {
          .a = 9,
  };

我得到:警告:空声明中无用的存储类说明符

如果我将其更改为

  static struct astr {
          int a;
  } something;

然后警告将被修复。

以下也没有给出警告

  struct astr {
          int a;
  };

  static const struct astr newastr = {
          .a = 9,
  }; 

有人可以解释这里发生了什么吗?

标签: cstructstatic

解决方案


当您有结构定义而没有声明任何变量时,您会收到警告。例如,以下将给出警告:

static struct s {
    int a;
};

这相当于:

struct s {
    int a;
};

它定义了结构s,但不声明任何变量。即,没有与之关联的存储,所以没有什么可以应用的static

但如果你这样做:

static struct s {
    int a;
} x;

然后没有警告,因为x除了定义结构之外,您还声明了变量s,因此static适用于x.

同样,如果struct s之前已定义,您可以执行以下操作:

static struct s x;

没有任何警告。当然,如果需要,您可以选择提供初始化程序。


推荐阅读