Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to initialize my global data in shared library?

I have a single class which does all the required initialization. currently i have declared a global object of this class type, which is being instantiated on library load. I've seen other ways, like delaring

BOOL APIENTRY DllMain

entry point for the shared library, and does the actual initialization on process attach.

does this differ from letting the implicit global initialization to its job? which way is better?

like image 562
sramij Avatar asked Nov 23 '25 05:11

sramij


1 Answers

This is what happens during C++ DLL startup:

  1. System calls DLL's entry point, generated by you compiler
  2. Entry point calls DllMainCRTStartup (name may differ), which initializes C/C++ runtimes and instantiates all global objects.
  3. DllMainCRTStartup then calls user-defined DllMain.

I personally prefer DllMain, because this way I can explicitly control order of initialization. When you use global objects in different compilation units, they will be initialized in random order which may bring some unexpected surprises 10 minutes before the deadline.

DllMain also let's you do per-thread initialization, which you can not achieve with global objects. However, it is not portable to other platforms.

P.S. You do NOT need mutex in DllMain, as all calls to it are already serialized under process-global critical section. I.e. it is guaranteed two threads will not enter it at the same time for any purpose. This is also the reason why you should not communicate with other threads, load other libraries etc. from this function; see MSDN article for explanation.

like image 67
hamstergene Avatar answered Nov 24 '25 22:11

hamstergene



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!