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++?
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With