Reference static global variable from a different file

387 Views Asked by At

I'm trying to understand static global variables. I've read that the static keyword makes a global variable "private", accessible only from the file it's been defined.

To test this I created a couple of files. file1.c:

#include <stdio.h>
#include "file2.c"

extern int a;
extern int b;

int main() {
  printf("%d\n", a);
  printf("%d\n", b);
  return 0;
}

And file2.c which consists only of the global variable definitions. One static and the other not to compare:

int a=1;
static int b=2;

After compiling file1.c, the output is:

1
2

Since b is static, I expected that it shouldn't be accessible from file1.c. Yet after declaring it with extern int b, file1.c was able to print it.

I thought static variables couldn't be accessed from other files. Why was I able to access a static variable from a different file?

1

There are 1 best solutions below

5
On BEST ANSWER

I've read that the static keyword makes a global variable "private", accessible only from the file it's been defined.

That is approximately correct, but very misleading if you don't recognize that the word "file" is being used as a simpler stand in for the more correct term "translation unit". The latter can be viewed as the composite code formed from a source file by (pre)processing all the #include and conditional-inclusion directives within. That forms one logical unit of source code for compilation ("translation" in the standard's terminology).

Thus, when one talks about static declarations being scoped to one file, one means a file intended to be the main file of a translation unit. We thereby identify the TU with that file. This is in fact the essential difference between header files (.h) and source files (.c) -- both contain C source code, but the latter are meant to be compilation starting points, whereas the former are not. That's also why one should never #include a .c file.

I thought static variables couldn't be accessed from other files. Why was I able to access a static variable from a different file?

Because you're interpreting "file" differently than it was meant in the claim you're referring to, and because you have violated the strong convention supporting that word usage by #includeing one .c file into another. You are compiling just one translation unit, and all file-scope declarations of all contributing files (filesystem sense) are visible within.