问题
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 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 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