I like to think of it this way.
You know how you have function prototypes and function bodies?
1 2 3 4 5 6
|
int myfunction(); // prototype
int myfunction() // has a body
{
return 0;
}
| |
The prototype just tells the compiler "this function exists somewhere", but doesn't actually give the actual function. Whereas the function body
is the whole function.
Every function can have
one and only one body, and only in 1 source file. If you have multiple function bodies in multiple cpp files, the linker will give you an error because it doesn't know which body to use for the function.
Variables are the same way:
1 2 3
|
extern int var; // variable "prototype"
int var; // variable "body"
| |
The extern keyword tells the compiler "this variable exists somewhere" but doesn't actually create the variable. Much like how the function prototype doesn't actually define a function.
The 'normal' non-extern variable (the "body") actually creates a variable, allocates space for it, and ties that variable name with that space in memory.
Just as with functions, if you have two global variables with the same name in two seperate cpp files, the linker will complain because you're creating
two seperate variables, each with their own memory. And the linker doesn't know which variable you intend to use.
EDIT:
That said, global variables are horrendous and you should avoid using them, of course.