Say I declare a header file with a variable:
int count;
Then in the source file, I want to use count
. Do I have to declare it as:
extern int count
Or can I just use it in my source file? All assuming that I have #include "someheader.h"
. Or should I just declare it in the source file? What is the difference between putting count
in the header file vs the source file? Or does it not matter?
You only want one count
variable, right? Well this line:
int count;
Defines a count
variable for you. If you stick that in multiple files (by including it in a header), then you'll have multiple count
variables, one for each file, and you'll get errors because they'll all have the same name.
All the extern
keyword does is say that there is a count
variable defined in some other file, and we're just letting the compiler know about it so we can use it in this file. So the extern
declaration is what you want to put in your header to be included by your other files. Put the int count;
definition in one source file.
If you did put that into the header, then yes, you could just use it in the source file without any further declaration (after the point where the header has been #include
d, anyway).
#include "someheader.h"
effectively just copies the contents of someheader.h
in, as if it had all been directly written in the including file at that point.
However, this is not the way you're supposed to use headers. int count;
is a tentative definition - you are supposed to only put declarations in header files. So someheader.h
should have:
extern int count;
(which is just a declaration), and exactly one source file in your application should define count
:
int count = 0;
The others can just #include "someheader.h"
and use count
.
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