tags:

views:

43

answers:

3

Hi, This is a new question after my long rant. The problem here is, I have a global vector<Base*> vObjs in my main application and I got Derived objs in each static lib linked to the application. If I specify the vObjs to have an init_priority of 101 and each obj in static libs to have say... 1000, is it guaranteed that vObjs will get its constructor called before objs in static libs? Thanks for any help.

A: 

If you are using GNU C++, they seem to guarantee the order of initialization( click here ). However I should note that if you really rely on the order of initialization then your design is fragile. Better look for alternatives when you just don't care about the order. HTH

Armen Tsirunyan
Actually, the higher the value passed to `init_priority`, the lower priority it has.
nakiya
@nakiya: My bad, edited
Armen Tsirunyan
+1  A: 

Global Variables have been been considered harmful for nearly forty years and yet people still insist on using them. Why?

Please reconsider your design as it is brittle and is going to provide a maintenance headache for many years to come.

Johnsyweb
http://stackoverflow.com/questions/3880380/static-lib-loading-related-problem-please-help That is why I need a global variable.
nakiya
Correction, that is why *you think* you need a global variable.
Johnsyweb
+1  A: 

Let me echo the other responses that you might want to reconsider using globals for this. However one possible (and I'm sure still flawed) improvement at least removes the need for init priority.

Instead of using a global vector, you create a function that returns a reference to a static local. The C++ rules make sure that the function static local is always initialized at the latest by its first use, so you don't have to worry about the vector not being initialized.

vector<LibInfo*>& get_gvLibInfo()
{
    vector<LibInfo*> gvLibInfo;
    return gvLibInfo;
}

Then your registration looks like:

vector<LibInfo*>& get_gvLibInfo();

void reglib()
{
    get_gvLibInfo().push_back(this);
}
Mark B
Thanks. I was going to use __attribute__((init_priority())) but this method is better it seems.
nakiya