I have an application which [unfortunately] contains quite some global variables. A recent crash-at-startup lead me to the following construction:
FILE1.CPP:
ClassX globalVariableX;
FILE2.CPP
ClassY globalVariableY;
Unfortunately, the constructor of class Y uses code in which globalVariableX is used.
Until now everything went fine because (coincidentally) FILE1.OBJ was linked in before FILE2.OBJ, meaning that globalVariableX is instantiated before globalVariableY.
Last week, a totally unrelated change in other files, caused the linker to link in FILE2.OBJ before FILE1.OBJ. Now globalVariableY is instantiated first, its constructer indirectly refers to globalVariableX, and crashes because globalVariableX has not been instantiated yet.
I know I should get rid of all the global variables as much as possible (please don’t start a debate about this).
But are there tools available that can help me to look up dependencies between global variables?
Or are there any tricks that I can use to see at run time if there are dependencies which I should get rid of (I was thinking about introducing a base-class for the global variables in which I could log the construction of global variables, but this is probably quite some work). Any other suggestions?
EDIT:
All of your answers are very good suggestions on how to prevent these nasty problems. But I was actually looking for a way to find these dependencies, not removing all global variables (or replacing them with another construction). Any ideas on tools that find these dependencies?
The usual solution is to rely on initialization on first use.
In C++, you can use local static (in functions) to get this behavior. In C++0x (but already implemented in major compilers) this is even guaranteed to be thread-safe (the initialization, at least).
There is still one issue though: such a scheme does not detect cyclic references. It could be akin to a recursion gone mad and thus blow your stack 😉