1

I have a small query, How to create and export Singleton class from DLL? that could be share across multiple modules of same application. My intention is to create a centralized custom logging system that would log in same file.

Any example or link will be appreciated.

Omkar
  • 2,129
  • 8
  • 33
  • 59
  • 1
    Does it really [need](http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/) to be a singleton? No point in making life harder for yourself than it has to be. – jalf Jun 06 '11 at 08:01

1 Answers1

3

The link ajitomatix posted is for a templated singleton, a non-template solution could look like this:

class LOGGING_API RtvcLogger
{
public:
  /// Use this method to retrieve the logging singleton
  static RtvcLogger& getInstance()
  {
    static RtvcLogger instance;
    return instance;
  }

  /// Destructor
  ~RtvcLogger(void);

  /// Sets the Log level for all loggers
  void setLevel(LOG_LEVEL eLevel);
  /// Sets the minimum logging level of the logger identified by sLogID provided it has been registered.
  void setLevel(const std::string& sLogID, LOG_LEVEL eLevel);

  /// Log function: logs to all registered public loggers
  void log(LOG_LEVEL eLevel, const std::string& sComponent, const std::string& sMessage);

protected:
  RtvcLogger(void);
  // Prohibit copying
  RtvcLogger(const RtvcLogger& rLogger);
  RtvcLogger operator=(const RtvcLogger& rLogger);
  ....
};

Where LOGGING_API is defined as

// Windows
#if defined(WIN32)
// Link dynamic
  #if defined(RTVC_LOGGING_DYN)
    #if defined(LOGGING_EXPORTS)
      #define LOGGING_API __declspec(dllexport)
    #else
      #define LOGGING_API __declspec(dllimport) 
    #endif
  #endif
#endif

// For Linux compilation && Windows static linking
#if !defined(LOGGING_API)
  #define LOGGING_API
#endif

It looks like you're already aware of this, but for completeness sake the Meyer's singleton works as long as your code is in a DLL on windows, if you link it as a static library, it won't work.

Ralf
  • 9,405
  • 2
  • 28
  • 46