How to write code to be executed before main() gets control?

c++

Solution

Initial answer

You could use a constructor of an object at `namespace` scope.

namespace {
struct Init
{
    Init()
    {
        // Initialization code here.
    }
} init_;
} // namespace

Beware, this has some limitations, especially on Windows. On Windows, the ctor is invoked with the loader lock held, thus you cannot do anything that would require loading DLLs and such. This includes initialization of WinSock because it can try to load external DLLs.

Update

According to some sources, you can work around this limitation by using `QueueUserAPC`. This technique has limitations as well, albeit different ones. I have used this and my experiments show that this only works if you are using Visual Studio and its C library as DLL, i.e., the MSVCRT.DLL, MSVCR100.DLL, etc. (`/MD` or `/MDd` switches)

Update 2

Here is a link to similar issue (mine, actually) with one important bit:

After some testing it seems that the APC method works if I queue the APC from DllMain() but it does not work if I queue the APC from a ctor of a static global instance of a class.

Problem

I am porting a class to C++ and need to execute some initialization code before the first instance of my class is created; executing the code before `main()` gets control suits me. How to do it in C++?

Original source

Related problems