In C, how do I restrict the scope of a global variable to the file in which it's declared?

c, scope

Solution

You #included bar.c, which has the effect of causing the preprocessor to literally copy the contents of bar.c into foo.c before the compiler touches it.

Try getting rid of the include, but telling your compiler to compile both files (e.g. `gcc foo.c bar.c`) and watch it complain as you expect.

Edit: I suppose the primary confusion is between the compiler and the preprocessor. Language rules are enforced by the compiler. The preprocessor runs before the compiler, and acts on those commands prefixed by #. All the preprocessor does is manipulate plain text. It doesn't parse the code or try to interpret the meaning of the code in any way. The "#include" directive is very literal - it tells the preprocessor "insert the contents of this file here". This is why you normally only use #include on .h (header) files, and you only place function prototypes and extern variable declarations in header files. Otherwise, you will end up compiling the same functions, or defining the same variables, multiple times, which is not legal.

Problem

I'm new to C. I have a book in front of me that explains C's "file scope", including sample code. But the code only declares and initializes a file scoped variable - it doesn't verify the variable's scope by, say, trying to access it in an illegal way. So! In the spirit of science, I constructed an experiment. File `bar.c`: ``` static char fileScopedVariable[] = "asdf"; ``` File `foo.c`: ``` #include <stdio.h> #include "bar.c" main() { printf("%s\n", fileScopedVariable); } ``` According to my book, and to Google, the call to `printf()` should fail - but it doesn't. `foo.exe` outputs the string "asdf" and terminates normally. I would very much like to use file scoping. What am I missing?

Original source