C++ a singleton class with dll

Viewed 11243

I created a static library with class:

class CLog
{
   private:
   CLog();
   ...
   ...
   public:
   static CLog& GetInstance()                                
   {
           static CLog Instance;
           return Instance;
   }
   void Write(char *cpPr);
};
#define Log CLog::GetInstance()

This library is linked to a dll and a main program. The dll is loaded by LoadLibrary. In this case is obvious that calling Log.Write in a main exe and in dll, creates two separate instances of CLog. Any ideas how to work around this issue and still provide dynamic loading a dll?

3 Answers

Here's a simple library that supports to share the same singleton instance between dynamical libraries and exectuable. (tested on win, linux, macos)

To get the singleton instance of type T, just use singleton<T>() is OK.

https://github.com/xhawk18/singleton-cpp

#include "singleton-cpp/singleton.h"

MyObject &obj = singleton<MyObject>();
Related