【发布时间】:2019-06-16 10:24:44
【问题描述】:
当您在全局范围内定义 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;
}
我希望我能够在全局范围内定义结构的成员。
【问题讨论】:
-
试试这个。在全局范围内初始化变量 x。
int x = 5;然后在全局范围内重新分配其值x = 10;并且它不会编译。您不能在函数之外分配值。不过,您可以初始化值。 -
我试过了,它确实编译和工作了吗?编辑:我打错了,我明白你的意思。这是为什么呢?
-
是的。它不应该编译。编辑:我在回答中做了一个小解释。