The file that actually gets compiled is what the preprocessor spits out, not the source.c file.
So, if you put int count;
in a header file, every source file which #include
s the header will get it's own copy of count
.
In this case you'll have source which looks like this:
int count;
...
extern int count;
If you're using gcc, try gcc -E file.c
. This will instruct it to only run the preprocessor so you can see what's actually being fed to the compiler.
As @Neil suggested, you will want to declare int count;
in a C file. If you want another C file to be able to reference this variable, then you put an extern int count;
declaration in the other file (or in a header file that the other includes).
Incidentally, one of my favorite C bugs is when you declare a global variable like this: int count;
, then in another file you declare another global variable with the same name, but a different type float count;
. In the first file, you say count = 1
, and all the sudden the count
in the second file becomes -0.0
. Moral of the story? Avoid global variables, and if you must use them, make them static
.
List item