当您全局定义 struct
时,为什么不能也全局定义结构成员(除了使用初始化语法之外)?我从 clang 得到的错误是 system_1 有一个“未知类型名称”。
如果您在函数中定义结构,例如 main()
,那么您不会遇到任何问题。
typedef struct Light_System {
int redLightPin;
int yellowLightPin;
int blueLightPin;
} Light_System;
Light_System system_1;
# "Light_System system_1 = {4, 0, 0}" works
system_1.redLightPin = 4; # doesn't work
int main(int argc, char *argv[]) {
# placing everything in here works
# placing just "system_1.redLightPin = 4;" here makes it work.
printf("%d\n", system_1.redLightPin);
return 0;
}
我希望我能够在全局范围内定义结构的成员。
最佳答案
When you define a struct globally, why can't you define the structure members globally (outside of using the initializer syntax)?
因为您要做的不是定义或初始化。这是一个任务。您可以在全局范围内声明、定义和初始化,但不能赋值。
这不仅适用于结构。它也适用于变量。在函数之外,您只能声明和初始化变量。你不能做常规作业,或者其他任何事情。我不能 100% 确定细节,但我相当有信心您无法在全局范围内做任何在编译期间无法完成的事情。
这样就可以了:
int x=5;
但不是这个:
int x;
x = 5;
好吧,实际上它是有效的,但会产生关于 warning: data definition has no type or storage class
和 warning: type defaults to 'int' in declaration of 'x' 的神秘警告
然而,仅仅因为它编译,它不会做你认为它会做的事。实际上,你不理解的神秘警告通常是一个很好的指标,表明代码会做一些你既不想也不理解的事情。这段代码所做的是 x
的 隐式重新声明,然后是 初始化。如果之前没有初始化是允许的,所以这是无效的:
int x = 3;
x = 5; // Not ok, because x is already initialized
这里的错误信息清楚地说明了为什么前面的例子被编译:error: redefinition of ‘x’
。
同样,这也是无效的:
int x = foo();
它给出了这个错误:
main.c:3:7: error: initializer element is not constant
int x = foo();
^~~
关于c - 为什么不能全局定义结构成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56617945/