One class instance differs in exe and dll GUI

In my GUI application (MFC), I use dll to display something on the screen. I have a static library for which there is a singleton class for this. for example: sing.lib. I include sing.lib in the application project (exe) and the dll project (both use this singleton class)

The problem is the instance included in exe and the dll is different. Both constructor calls! see the singleton element code snippet.

class A { private: A(); virtual ~A(); static A* m_pInstance; public: static A* GetInstance() { if (NULL == m_pInstance) { m_pInstance = new A(); } return m_pInstance; } } 
+4
source share
3 answers

If you want a singleton instance to be shared between dll and exe, put its definition in a dynamic link library instead of a static library.

In general, if you want some data to be global and unique, you should not put it in a static library.

Consider

 //static lib int CurrentCounter =0; int getNextCounter() { return CurrentCounter; } 

such code in a static library. In your case, if both exe and dll links against this library get their own CurrentCounter . Thus, exe and dll can have different CurrentCounter values.

+5
source

The static library is associated with both the EXE and the DLL, so both binaries have a “copy” of your class, so different singletones are design behavior. This type of singlet is "binary" rather than process.

You need a dynamic library for the syntax of the complete process so that your EXE uses the DLL export and deals with the class associated with the DLL.

+2
source

Each binary that the static library is associated with will have its own copy of the class.

+1
source

Source: https://habr.com/ru/post/1384313/


All Articles