1. 程式人生 > 其它 >QT 使用Q_OBJECT匯出動態連結庫 dll 和使用報錯:C2491

QT 使用Q_OBJECT匯出動態連結庫 dll 和使用報錯:C2491

技術標籤:qt

先吐槽一下Windows的匯出庫形式真的很麻煩

假設你的dll標頭檔案

#if defined(_MSC_VER) || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
#  define Q_DECL_EXPORT __declspec(dllexport)
#  define Q_DECL_IMPORT __declspec(dllimport)
#endif
#if defined(LIBRARY) # define TESTLIB_EXPORT Q_DECL_EXPORT #else # define TESTLIB_EXPORT Q_DECL_IMPORT #endif #include "QObject" class TESTLIB_EXPORT TestClass : public QObject { Q_OBJECT // 此處使用了 Q_Object巨集 ...... }

當你編譯動態庫的時候, 編譯的是

#  define Q_DECL_EXPORT __declspec(dllexport)

這樣才會匯出lib檔案, 不加這一條是不會匯出lib, 只有dll

當用戶使用你的庫的時候, 編譯的是

#  define Q_DECL_IMPORT __declspec(dllimport)

因為你的動態庫專案.pro檔案裡面有這一行

DEFINES += LIBRARY

但是使用者使用你的動態庫無法編譯通過的, 因為你的庫帶有帶有Q_OBJECT 巨集, 會報C2491的錯誤。
在這裡插入圖片描述

原因就是 __declspec(dllimport)
你需要把這個遮蔽掉
即為

#if defined(_MSC_VER) || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
# define Q_DECL_EXPORT __declspec(dllexport) # define Q_DECL_IMPORT __declspec(dllimport) #endif #if defined(LIBRARY) # define TESTLIB_EXPORT Q_DECL_EXPORT #else # define TESTLIB_EXPORT //此處刪除 Q_DECL_IMPORT #endif #include "QObject" class TESTLIB_EXPORT TestClass : public QObject { Q_OBJECT // 此處使用了 Q_Object巨集 ...... }