如何从另一个文件访问静态变量?
如何从另一个文件访问静态变量?静态变量没有文件作用域吗?
bash-3.2$ ls
a.c b.c
bash-3.2$ cat a.c
#include <stdio.h>
static int s = 100;
int fn()
{
/* some code */
}
bash-3.2$ cat b.c
#include <stdio.h>
#include "a.c"
extern int s;
int main()
{
printf("s = %d \n",s);
return 0;
}
bash-3.2$ gcc b.c
bash-3.2$ a.exe
s = 100
How am I able to access a static variable from another file? Doesn't static variable have a file scope?
bash-3.2$ ls
a.c b.c
bash-3.2$ cat a.c
#include <stdio.h>
static int s = 100;
int fn()
{
/* some code */
}
bash-3.2$ cat b.c
#include <stdio.h>
#include "a.c"
extern int s;
int main()
{
printf("s = %d \n",s);
return 0;
}
bash-3.2$ gcc b.c
bash-3.2$ a.exe
s = 100
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您已将一个文件包含到另一个文件中 - 非常糟糕的做法。从C编译器的角度来看,两个文件形成一个翻译单元,因为C预处理器将
ac
的内容插入到bc
中。如果有两个独立的翻译单元,一个单元无法访问另一个单元的静态,但这不是您的情况。
如果删除
#include "ac"
行并按照应有的方式进行编译:gcc ac bc
,您将收到unresolved external
错误>s。You have included one file into another - very bad practice. From C compiler point of view, both files form one translation unit, because C preprocessor inserts the content of
a.c
intob.c
.In case of two separate translation units, one unit cannot access
static
s of another, but it's not your case.If you remove
#include "a.c"
line and compile like it should be:gcc a.c b.c
, you will getunresolved external
error fors
.它来自一个单独的文件,但您打印的内容不是来自单独的翻译单元,因为您
#include
来自<的整个ac
代码>bc。static
对象是由所有包含的文件组成的翻译单元的本地对象,而不是单个源文件的本地对象。It's from a separate file, but what you're printing is not from a separate translation unit as you
#include
the whole ofa.c
fromb.c
.static
objects are local to a translation unit, which consists of all included files, and not to a single source file.