Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force destruction order of static objects in different dlls?

I have 2 static objects in 2 different dlls:

An object Resources (which is a singleton), and an object User. Object User in its destructor has to access object Resources.

How can I force object Resources not to be destructed before object User?

like image 515
Igor Avatar asked May 16 '09 10:05

Igor


3 Answers

In the case you really want to get 2 separated Dlls I may have some hints for you: you may consider the use of FreeLibrary() from Windows API. As stated by msdn FreeLibrary() decrements a reference counter for the Dll which is unloaded when the counter reaches 0.

Drawback: using FreeLibrary() implies you are loading it with LoadLibrary() (msdn link) and calling function from this library implies you are using the GetProcAddress() function, which may lead to really ugly code. And it may imply some change in your code too - as getting global variable poiting to the Dll's functions in order to store each functions' address ...

If you want to implement it:

  1. you must load&free the library from your main() function of your process,
  2. and also load and free the library from the Dll implenting the User class. Implement it in the DllMain() function for this Dll, when the reason is DLL_PROCESS_DETACH (see mdsn's DllMain link.

Thus it will unload the "Resource" library only once the "User" library have finish with it.

Have a try if you will and let tell me if it works as I never implemented it..

Ps: I've posta second answer to your question to get a meaningful separation between the two answers as I (try to) detail both of them. I don't want you to mix them up and get confused ...

like image 153
yves Baumes Avatar answered Nov 15 '22 04:11

yves Baumes


Global objects are destroyed when their corresponding DLL is unloaded. So as your 'User' dll is probably dependent of your 'Resource' dll, you are in trouble: 'resource' will always be destroyed before 'user'.

I'm also interested by a good answer to this question, if one exist. Until now, I'm using a cleanup function that must be called by application before it quits, and I only keep harmless code in destructors.

like image 23
Jem Avatar answered Nov 15 '22 03:11

Jem


I don't think you can change order of destruction of globals that are in different modules. Any chance of adding some reference counting?

like image 32
sean e Avatar answered Nov 15 '22 05:11

sean e