What you "know" is wrong. Who told you that? You apparently don't understand what you are talking about.
Forget for a minute about include files. The are included before compilation. Imagine that they are all substituted with their texts (this is what really happens before compilation). Then you will have only CPP files. Each one is compiled separately into some object file; you will have as many object files as CPP files. Then the executable code is created by
linking together all object files. So, each CPP file is compiled into a separate
compilation unit.
How one can use variables or constants across compilation units. With functions and types, it's easy, but how about the variables initialized at the point of definitions, and constants? The "trick" is: there are
declarations and
definitions (for functions, too, but we are talking about variables and constants). When a variable or constant is initialized, it has to be a definition; it defines really existing object. This should be done only once in a compilation unit. Think by yourself: if, by the effect of all you "includes", you have two different declaration, should it compile? For example:
const char * lp = "abc";
const char * lp = "cde";
Of course, not. How a compiler would "know" what value do you really need "abc" or "cde"? (Note: this is not assignment; this is initialization!) If you understand that, what's the difference if you initialize with the same value. This won't compile, too:
const char * lp = "abc";
const char * lp = "abc";
The real reason is: you cannot have two really existing objects with the same name, because the compiler would not "know" which one to link when you mention the name anywhere in code.
In contrast to this situation, you can have one or more declarations of the same object using the word
extern
:
http://msdn.microsoft.com/en-us/library/0603949d.aspx[
^].
Note that it does not mean that the definition should be in a separate compilation unit. It only say that it has the
static duration. If the compiler cannot find the static definition in the scope of the current C++ file (same compilation unit), it creates a reference by name in the object file, and then the linker will try to find the definition in other object files.
—SA