0

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?

glebB
  • 23
  • 5
  • What sort of library – M.M Mar 15 '16 at 05:20
  • It would be better if you post a MCVE. For example, perhaps `main()` finds `getGlobalReg().empty()` true because you never made a `Compatible` object yet. We can't tell this from what you have posted. – M.M Mar 15 '16 at 05:22
  • You can: the last line of file2.cpp initializes a static object of class Compatible. An MCVE can be constructed by adding a main.cpp containing int main() { cout << "Size of the global object list: " << getGlobalReg().size() << endl; return 0; } – glebB Mar 15 '16 at 06:08
  • I understand the problem is that a static object which is never explicitly used, is never created if it's contained in a library... – glebB Mar 15 '16 at 06:11
  • The technical difficulty is explained here: http://stackoverflow.com/questions/1939899/how-do-i-make-an-unreferenced-object-load-in-c – glebB Mar 15 '16 at 06:36
  • You hadn't added that line when I made my comment. According to the C++ Standard, initialization of global variable may be delayed until the first call of a function in the same unit. Perhaps you could try adding a function to file2.cpp that you call (and will as side-effect make `__auto_reg` be created). BTW you should not use double-underscore in your own code, it's reserved for implementation use. Also it would be good to try and minimize how much you rely on static initialization order. – M.M Mar 15 '16 at 06:47

1 Answers1

0

Sounds like you want to use the Singleton Design Pattern. See if the following link winds your watch. https://sourcemaking.com/design_patterns/singleton/cpp/2

Colin Helms
  • 164
  • 2
  • 10
  • The singleton case can be solved easier - just reference the static object from the main file. I want to add several objects. – glebB Mar 15 '16 at 06:36