Created attachment 31902 [details] PoC code Modifications of global variables are sometimes not carried out properly when FLTO is enabled. Short PoC follows. // FILE bug-flto.cpp // #include <vector> #include <stdio.h> #include "shared.h" std::vector<int> globalvec; S1::S1() { printf("S1() called\n"); globalvec.push_back(42); printf("S1() globalvec.size() = %d\n", (int) globalvec.size()); } int main() { printf("main globalvec.size() = %d\n", (int) globalvec.size()); return 0; } // FILE tu2.cpp #include "shared.h" S1 s1; // FILE shared.h #pragma once struct S1 { S1(); }; // FILE Makefile run: bug-flto ./bug-flto bug-flto: bug-flto.o tu2.o g++-4.8 -O -flto -obug-flto bug-flto.o tu2.o bug-flto.o: bug-flto.cpp g++-4.8 -O -flto -obug-flto.o -c bug-flto.cpp tu2.o: tu2.cpp g++-4.8 -O -flto -otu2.o -c tu2.cpp clean: rm *.o rm
Output I get is: S1() called S1() globalvec.size() = 1 main globalvec.size() = 0 tested with g++-4.8 (Ubuntu 4.8.1-2ubuntu1~12.04) 4.8.1
The order of initializing s1 and globalvec is undefined in C++ and that is the effect you are seeing. If s1 and globalvec are declared in the same TU, the order is defined by the order in the source itself.
So in this case here, s1 is being initialized first and then globalvec gets initialized which changes the size back to 0.
(In reply to Andrew Pinski from comment #3) > So in this case here, s1 is being initialized first and then globalvec gets > initialized which changes the size back to 0. Thanks for the explanation. I've verified this does appear to be the case.