How am I able to access a static variable from another file? [duplicate]

那年仲夏 提交于 2019-12-13 04:44:37

问题


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 

回答1:


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 into b.c.

In case of two separate translation units, one unit cannot access statics 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 get unresolved external error for s.




回答2:


It's from a separate file, but what you're printing is not from a separate translation unit as you #include the whole of a.c from b.c.

static objects are local to a translation unit, which consists of all included files, and not to a single source file.



来源:https://stackoverflow.com/questions/2311249/how-am-i-able-to-access-a-static-variable-from-another-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!