2011-06-06 15 views
1

我有一個小的查詢,如何創建並從DLL導出Singleton類?可以跨同一應用程序的多個模塊共享。我的目的是創建一個集中的自定義日誌記錄系統,可以登錄同一個文件。從DLL中創建和導出C++單例類

任何示例或鏈接將不勝感激。

+1

它真的[需要](http://jalf.dk/blog/2010/03/singletons-solving-problems-you-didnt-know-you-never-had-since-1995/)是一個單身?沒有必要讓自己比自己的生活更難。 – jalf 2011-06-06 08:01:40

回答

3

發佈的鏈接ajitomatix是一個模板單身,非模板解決方案看起來是這樣的:

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); 
    .... 
}; 

凡LOGGING_API被定義爲

// 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 

看起來你已經意識到這一點,但爲了完整起見,只要您的代碼位於Windows上的DLL中,如果將其作爲靜態庫進行鏈接,Meyer的單例將不起作用。

+0

謝謝你的清晰和明確的解釋.....我一定會嘗試這個。 – Omkar 2011-06-07 04:55:33