Asking about static variable construction.

I want to find a way to add some codes to execute before main when any executable program link my library, which may be a static library or dynamic, shared object, etc.

At first I write it in this way:
1
2
3
4
5
6
7
8
9
10
namespace
{
    struct InitializeCode
    {
        InitializeCode()
        {
            // my initilize codes...
        }
    }initializer;
}


This code is inside my library. I throught it will be execute for the static variable initializer will be construct beform main function. But when I link to a test program, the initilize codes is never execute, and in fact the initializer is not constructed at all.
I don't know whether is it an optimize of the compiler, but I change the codes to the below style:
1
2
3
4
5
6
7
8
9
namespace
{
    int initialize_code()
    {
        // my initilize codes...
        return 0;
    }
    int initialize_dummy = initialize_code();
}

And it works.
I wonder whether this behavior is standard and protable, or it compiler special(I use vc9), or it is absolutely stochastic.

Is there any suggestion about this? Thank you~
To have a portable solution, add a function called yourlibrary_init or something like that and make it mandatory to call it before any other use of your library
Topic archived. No new replies allowed.