Sorry I totally missed your Nov 2 reply. Whoops.
FWIW, global variables should be avoided since they're usually a design disaster. I'd recommend you reconsider your usage of them here.
That said... if you really must use them...
I'm going to make an analogy between a global variable and a global function. A global function can have both a prototype and a body:
1 2 3 4 5 6
|
int myfunc(); // prototype
int myfunc() // body
{
return 0;
}
|
Typical usage is... you put the prototype in a header and the body in a cpp file.
1) If you don't put the prototype in the header, then other cpp files will get you an "undeclared identifier" compiler errors when you try to call the function --- the compiler won't know what function it is you're trying to call.
2) If you put the body in the header, then you'll get "multiple definition" linker errors. The linker will see each cpp file as having their own copy of the function and won't know which copy you want to call.
3) If you put the prototype in the header, but DON'T put the body in a cpp file, you'll get "unresolved external" linker errors. The linker will see you calling the function, but since the function has no body it won't be able to call it.
So long story short... the prototype can be in any number of cpp files (via being #included in a header)... but the body must be in exactly
ONE (and only one) cpp file.
Global variables are the same way.
|
extern int x; // variable "prototype"
|
|
int x; // variable "body"
|
The "body" in this case actually creates the variable. Whereas the "prototype" merely says 'this variable exists somewhere else'. So conceptually it's the same as with global functions. The same 3 rules listed above apply
So again... long story short.
|
extern int x; // this goes in a header
|
|
int x = 0; // this goes in ONE AND ONLY ONE cpp file
|
But again... I really want to stress how terrible of a design global vars usually are. I strongly recommend reconsidering.