This is the subject code:
externfile.cpp
int i = 10;
mainfile.cpp
#include <iostream>
using namespace std;
extern int i;
int main(int param)
{
cout << i << '\n';
int i = 0;
cout << i << '\n';
cout << ::i << '\n';
}
When compiling this program (using Visual Studio 2008), it works fine and the output will be:
10
0
10
which is not surprising for me, this is a matter of scopes.
But what makes me confused is: How could mainfile.cpp
file get the value of i
from another .cpp
file (externfile.cpp
in our case)? is it only because they reside in the same directory? or the same solution?
And in a better way: How are source files "merged" while compiling a project (with VS2008, if I should specify)? in what "order" are they placed? and how are they scoped?
A "normal" VC++ project1 instruct VC++ to compile each source file by itself to an "object file" (or object module), where the compiler leaves "placeholders" for symbols that aren't resolved yet (like external
variables or functions that are declared but not defined).
Then, all the object files are tied together by the linker, which ties them together to produce the final executable. During this passage, the "placeholders" are replaced by the actual address of the code/data they refer to that is defined in the various object files. If some needed definition is not found you get an undefined reference error, if some symbol is found more than once you get a multiple definition error2.
Fore more information about the classical model for linking, have a look at this article by Raymond Chen (and, if you are interested, to the whole series).
inline
functions and template
instantiations; in those cases, the linker just takes whatever it prefers (which shouldn't be a problem, since multiple definitions of such objects must be the same).