fileA.cpp:
#include <iostream>
extern int iA;
extern int iB= iA;
int main()
{
std::cout<<iA<<','<<iB;
}
fileB.cpp
extern int iB;
extern int iA = 2*iB;
Compiled and linked and ran, out come in the debug and release mode is 0,0
My question is how it works, why there is no issue in linking stage?
I'm using VC++2003.
The initialiser overrides the
extern
keyword, so there's nothing "magical" about this: you're just declaring and defining two completely unrelated variables in different translation units.From Standard for Programming Language C++ - Chapter 3.1:
Your program is thus equivalent to the following:
fileA.cpp
fileB.cpp
Both objects necessarily undergo static initialization (to bitwise all-zeroes) before anything else happens. When dynamic-initialization later takes place, depending on whether the static-storage-duration objects in fileA.cpp or fileB.cpp get initialised first (and you can't know what order that'll be) either
iB
is initialized to a zeroiA
(theniA
is initialized to2*iB
as expected), oriA
is initialised to a zeroiB
multiplied by two, which is still zero (theniB
is initialized to a zeroiA
).Either way, both objects are going to end up, via well-defined semantics, having a value of zero.