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?
Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function. That is, a global variable is available for use throughout your entire program after its declaration.
Block Scope: A Block is a set of statements enclosed within left and right braces i.e. '{' and '}' respectively. Blocks may be nested in C(a block may contain other blocks inside it). A variable declared inside a block is accessible in the block and all inner blocks of that block, but not accessible outside the block.
A scope is a region of the program, and the scope of variables refers to the area of the program where the variables can be accessed after its declaration. In C every variable defined in scope.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With