开发者

Creating and Exporting C++ Singleton Class from DLL

开发者 https://www.devze.com 2023-03-10 20:44 出处:网络
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

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 wou开发者_StackOverflowld log in same file.

Any example or link will be appreciated.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消