Well, a surprising result, never use your extern variables inside a function that runs before main.
Here’s an example:
In the header:
//extern test. the externs are giving 0's. struct Vector4f { float x,y,z,w; Vector4f():x(0),y(0),z(0),w(0){} Vector4f( float ix, float iy, float iz, float iw ) :x(ix),y(iy),z(iz),w(iw){} } ; extern Vector4f Red ; // This is the weird variable..
In the main.cpp file:
static map<char, Vector4f> initMapping() { map<char, Vector4f> mp ; mp.insert( make_pair( 'r', Red ) ) ; for( auto &p : mp ) printf( "%c: %f %f %f %f\n", p.first, p.second.x, p.second.y, p.second.z, p.second.w ); return mp ; } //Vector4f Red(1,0,0,1) ; // if this is here, Red has (1,0,0,1) map<char, Vector4f> colorMapping = initMapping() ; Vector4f Red(1,0,0,1) ; // if Red is only given its value HERE, when the static ctor runs, Red will be (0,0,0,0) int main(int argc, const char * argv[]) { for( auto &p : colorMapping ) printf( "%c: %f %f %f %f\n", p.first, p.second.x, p.second.y, p.second.z, p.second.w ); }
So those 2 declarations of Vector4f Red
(without extern qualifier) in the cpp are the issue here. If the compiler runs into the Vector4f Red(1,0,0,1) ;
BEFORE running SomeStruct::initMapping()
, then the mapping has the correct value for Red in it. If the compiler first runs into Vector4f Red(1,0,0,1)
only __after__ running SomeStruct::initMapping()
, then the value of Red inside the map would be all 0’s.
One Trackback/Pingback
[…] Never use your extern variables inside a function that runs before main. […]