【发布时间】:2020-05-27 15:08:24
【问题描述】:
首先,从这里开始:
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,它会起作用)。
第二个问题
#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 跨多个调用的值,从这个意义上说,我希望有一个成员(在这种情况下为bool is_there) preserve 值跨越struct foo1 类型的每个变量(它的实例)。那么为什么不可能呢?
问题编号 3
另外,有人可以从中解释错误(更一般意义上):
error: expected specifier-qualifier-list before ‘static’
编辑:
从cmets,我不太了解存储类的概念,我只从asm知道,有data/text/bss segments,那么是不是说static var在read-only部分内存中有地址?或者c中storage class与asm相关的概念是什么?
【问题讨论】:
-
当您通过
malloc为该实例分配内存时,在结构中拥有static成员的预期结果是什么?为不同的成员设置不同的存储类别会产生什么影响?还是在成员和结构本身之间?结构只是某些数据对象的蓝图。它没有具体说明这将在哪里结束。您似乎混淆了 C 中的静态对象和 C++ 中的静态类 -
@Gerhardh 我知道这只是“蓝图”,但我怎样才能拥有一个成员
pre-defined?我只是不想为该类型的每个 var 初始化相同的值,因为它可以拥有所有这些值。我认为这就是static的用途 -
@Gerhardh 我没有将
C++与纯C混合,我的意思是struct s_t类型的变量(不是类的实例)我只是简写为instance,但这个问题只针对Clang。 -
C 中不存在静态成员。预定义值也是如此。
-
蓝图定义了布局。它不会带来所有的家具。