Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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++?

like image 592
kludg Avatar asked Oct 22 '25 17:10

kludg


1 Answers

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.

like image 197
wilx Avatar answered Oct 24 '25 07:10

wilx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!