首页 > 解决方案 > 为什么结构中不可能有静态成员?

问题描述

首先,从这里:

static struct foo1 { //private struct, just for this file
    int a;
};

int main (void) {
    struct foo1 a = {10};
    return 0;
}

问题编号 1

我会收到警告:

warning: useless storage class specifier in empty declaration
 };

这是什么意思?为什么是static“无用的存储类说明符”?在其他上下文中(函数中的静态局部变量或全局静态,我想申请 struct foo1,它会起作用)。

问题2

#include <stdbool.h>
static struct s_t{ //private struct (for this file only) 
    static bool is_there = false; // defaul (pre-defined) value for all instances
    int value;
};

int main (void) {}

为什么不能为struct s_tc 中的所有类型的变量提供静态的预定义值?我只是想模拟与函数中相同的功能static local var->在多个调用中保留bool is_there值,从这个意义上说,我希望有一个成员(在本例中)在每个类型的 var 中保留struct foo1值(它的实例)。那么为什么不可能呢?

问题3

另外,有人可以从中解释错误(在更一般的意义上):

error: expected specifier-qualifier-list before ‘static’

编辑:从评论中,我不太了解存储类的概念,我只从 asm 中知道,有data/text/bss segments,所以这是否意味着在部分内存static var中有地址?或者与asm相关read-only的in c的概念是什么?storage class

标签: cstructstatic

解决方案


因为 struct 就像一个类型或一个对象,当你在 C 中声明一个静态成员时,它会像:

static int a = 0;

在这种情况下,“int”就像你声明的结构类型,所以如果你想创建一个结构静态成员,只需这样做:

static s_t a;

推荐阅读