Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single class instance is different in GUI exe and dll

In my GUI application (MFC) I am using a dll to display something in the screen. I have a static library which having a singleton class for this. eg: sing.lib. I am including sing.lib in application (exe) project and in dll project(coz both uses this singleton class)

Issue is the instance getting in exe and in dll is different. Both calls the constructor!! see the singleton class 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;
    }
}
like image 502
sdev Avatar asked Feb 23 '23 05:02

sdev


2 Answers

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

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

Consider

//static lib

int CurrentCounter =0;

int getNextCounter()
{
    return CurrentCounter;
}

such a code in static library. In your case if both the exe and dll link against this library each will get its own CurrentCounter. So exe and dll can have different values of CurrentCounter at the same time.

like image 167
parapura rajkumar Avatar answered Mar 01 '23 22:03

parapura rajkumar


Static library is linked into both EXE and DLL and so both of the binaries have "a copy of" your class, so dfiferent singletons are behavior by design. This sort of singletons are "per binary" rather than per process.

You need a dynamic library for true process wide singleton so that your EXE would use DLL exports and would deal with class linked into DLL.

like image 37
Roman R. Avatar answered Mar 01 '23 23:03

Roman R.