[英]can static declared global variable can be accessed with extern in another file?
I have one doubt if i declared global variable with static. 如果我用静态声明全局变量,我有一个疑问。
static int a=5;
main()
{
func();
}
can it be access in another file2.c using extern ? 可以使用extern在另一个file2.c中访问吗?
func()
{
extern int a;
printf(a);
}
or only global variable declared without static can be access using extern? 或者只使用extern来声明没有静态声明的全局变量?
No! 没有!
static
limits the scope of the variable to same translation unit . static
将变量的范围限制为相同的转换单元 。
static
gives the variable an Internal Linkage and this variable cannot be accessed beyond the translation unit in which was created. static
为变量提供内部链接,并且在创建的转换单元之外无法访问此变量。
If you need to access a variable accross different files just drop the static
keyword. 如果需要访问不同文件中的变量,只需删除
static
关键字即可。
No. A a
in file1.c names a variable with internal linkage . 编号A
a
在file1.c中的名称具有内部链接的变量。 The same name used from a different translation unit will refer to a different variable. 从不同的翻译单元使用的相同名称将引用不同的变量。 That might also have internal linkage or it might (as in this case) have external linkage .
这可能也有内部联系,或者可能(如本案例中)有外部联系 。
Within the same file you can refer to a file scoped variable with internal linkage with extern
, though. 但是,在同一个文件中,您可以引用带有与
extern
内部链接的文件范围变量。
static int a;
int main(void) {
extern int a; // still has internal linkage
printf("%d\n", a);
}
That seems to be a misunderstanding of the two meanings of static: 这似乎是对静态的两个含义的误解:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.