C 中全局变量的定义何时是有条件的?
When is a definition of a global variable in C conditional?
如果我说
int i=8;
在每个函数之外,这个全局变量的定义是暂定的吗?为什么?
编辑:我将 'conditional' 更改为 暂定 ,我翻译错了。
如果您在函数作用域外声明变量,那么它有 static storage duration and by default external linkage. It means that the variable is accessible everywhere in the current translation unit (i.e. the current C file produced by the pre-processor). The variable is also accessible in other translation units, but you need to either declare it there as extern int i;
or tentatively define it as int i;
. Note that if you define the variable as static int i = 8;
at file scope, then the variable will have internal linkage,您将无法在其他翻译单元中使用它,即使在那里声明为 extern int i;
。
这里没有条件,我不知道你说的这个词是什么意思。
编辑
不,你的不是 tentative definition。
如果您按照说明定义全局变量,那么在该变量之前定义的任何函数都不会知道该变量,除非在该函数之前或函数内进行了某些声明。
void foo () {
extern int i; /* declare presence of global i */
/* code that uses i */
}
int i=8;
void bar () {
/* code that uses i, does not need declaration */
}
全局的暂定定义是没有初始值设定项的裸声明。
int i; /* tentative definition */
void foo () {
/* code that uses i */
}
暂定定义允许 i
像在前向声明中一样使用,但是,除非找到 i
的显式外部定义,否则它也将被视为默认初始化的外部定义。
如果我说
int i=8;
在每个函数之外,这个全局变量的定义是暂定的吗?为什么?
编辑:我将 'conditional' 更改为 暂定 ,我翻译错了。
如果您在函数作用域外声明变量,那么它有 static storage duration and by default external linkage. It means that the variable is accessible everywhere in the current translation unit (i.e. the current C file produced by the pre-processor). The variable is also accessible in other translation units, but you need to either declare it there as extern int i;
or tentatively define it as int i;
. Note that if you define the variable as static int i = 8;
at file scope, then the variable will have internal linkage,您将无法在其他翻译单元中使用它,即使在那里声明为 extern int i;
。
这里没有条件,我不知道你说的这个词是什么意思。
编辑
不,你的不是 tentative definition。
如果您按照说明定义全局变量,那么在该变量之前定义的任何函数都不会知道该变量,除非在该函数之前或函数内进行了某些声明。
void foo () {
extern int i; /* declare presence of global i */
/* code that uses i */
}
int i=8;
void bar () {
/* code that uses i, does not need declaration */
}
全局的暂定定义是没有初始值设定项的裸声明。
int i; /* tentative definition */
void foo () {
/* code that uses i */
}
暂定定义允许 i
像在前向声明中一样使用,但是,除非找到 i
的显式外部定义,否则它也将被视为默认初始化的外部定义。