问题描述
在我的#include
指令之后,在文件顶部定义了以下变量;
I having the following variables defined at the top of my file right after my #include
directives;
int a = 5;
int b = a;
但是我得到一个编译时错误.我知道全局变量隐式具有静态存储持续时间,但是我不确定这与导致此错误的原因或方式有关.
But I get a compile time error. I know that global variables implicitly have static storage duration, but I'm not sure how or if this is related to the cause of this error.
推荐答案
正如您所说,全局变量隐式具有静态存储持续时间.这是因为全局变量是在编译时初始化的.因此,这正是您遇到错误的原因.
As you said, global variables implicitly have static storage duration. This is because global variables are initialised during compile time. So this is precisely the reason why you are getting an error.
来自 C99 Standard 6.7.8 :
要跳过此规则,可以使用以下技巧".
To get past this rule, you could use the following "trick".
int a = 5;
int b;
int main()
{
b = a;
//rest of code goes here.
}
这篇关于用C中的变量初始化全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!