首先,从这里:
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
是“无用的存储类说明符”?在其他上下文中(函数中的静态局部变量,或全局静态,我想将其应用于结构 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) {}
为什么在 c 中不可能为所有 struct s_t
类型的变量都设置静态预定义值?我只是想模拟与函数 static local var
中相同的功能 -> preserve value across multiple calls,从这个意义上说,我想要一个成员( bool is_there
在这种情况下) preserve 类型 struct foo1
(它的实例)的每个变量的值。那为什么不可能呢?
问题编号 3
此外,有人可以从中解释错误(在更一般意义上):
error: expected specifier-qualifier-list before ‘static’
编辑:
从评论看,我不是很懂存储类的概念,我只从asm知道,有data/text/bss segments
,那是不是代表static var
有地址在内存的只读
部分?或者c中与asm相关的storage class
是什么概念?
最佳答案
因为
static struct foo1 { ...
只是一个结构定义,而不是一个变量。当你声明结构的实例时,你应该添加static
。我更喜欢这种风格:typedef struct { int a; }foo_t; static foo_t a = {10};
因为 C 根本没有像 C++ 那样的静态成员变量。在 C 中,将存储或类型说明符添加到单个结构成员是毫无用处的。而是将其放在分配的变量上。
TL;DR 它只是对您的语法没有任何意义,因为您不能在那里使用
static
。除非您对语言语法非常感兴趣,否则别无他法。static
是一个存储类说明符,const
等是类型限定符 和int
etc 是一个类型说明符。术语specifier-qualifier list 来自结构的正式 C 语法,除非您正在制作编译器,否则阅读起来并不是很有趣。声明结构成员时,您有两种选择 (C17 6.7.2.1):specifier-qualifier-list: type-specifier specifier-qualifier-list(opt) type-qualifier specifier-qualifier-list(opt)
static
不符合两者的要求,作为存储类说明符,所以编译器说“什么!这不是我期望找到的说明符-限定符列表,它在哪里?”(是的,它是递归的,因此您可以有多个类型说明符或类型限定符,例如
const long const const int value;
。因为 C 代表 Crazy。)
关于c - 为什么在结构中不可能有静态成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62046434/