c - 为什么结构中不可能有静态成员?
问题描述
首先,从这里:
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_t
c 中的所有类型的变量提供静态的预定义值?我只是想模拟与函数中相同的功能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
解决方案
因为 struct 就像一个类型或一个对象,当你在 C 中声明一个静态成员时,它会像:
static int a = 0;
在这种情况下,“int”就像你声明的结构类型,所以如果你想创建一个结构静态成员,只需这样做:
static s_t a;
推荐阅读
- php - WordPress 中年存档的问题
- arrays - 带有 2 个匹配字符串的 Swift5 过滤器列表
- python - 如何从嵌套字典中提取值作为 Pandas DataFrames
- python - 使用 Paramiko 检索所有主机密钥(如 ssh-keyscan)
- flutter - 如何将任何 Dart 代码片段格式化为字符串输出
- python - VS Code 没有从 launch.json 中获取 args 列表
- c# - 如何通过 c# 将图像(条形码图像)传递给 rdlc 文件
- python-3.x - 我应该怎么做才能让新的小部件始终落后于 kivy 中的旧小部件?
- java - 如何在另一个线程上开始解析 Volley
- matlab - 通过 Jupyter Notebook 在 VSCode 中编码 MATLAB 不会因错误而停止执行