I want to have a global list of certain objects which is populated automatically when a compatible class is linked to the executable. I've come up with a method but it does not work when the 'compatible class' is put into a library.
The list should obviously be initialized before use, so I've put it as a static variable in a function. For example, I have file1.cpp as follows:
vector<int>& getGlobalReg() {
static vector<int> __globalReg;
return __globalReg;
}
The header file1.h defines access to that func:
vector<int>& getGlobalReg();
An object (in this case an integer) would be automatically registered by a linked file2.cpp e.g. as follows:
class Compatible {
public:
Compatible() {
getGlobalReg().push_back(2);
}
};
Compatible __auto_reg;
When linking all that together, all fine. When putting file1.cpp into lib1 and file2.cpp into lib2 (which uses lib1), the executable which uses lib2 finds getGlobalReg() empty. Observing this in g++ and MSVC 2013.
Is this a proper way for automatic registration of objects in a 'global list'? Can it be modified to work in the proposed linking scenario and where are the corresponding linking rules defined?