我正在尝试创建线程安全单例类(MySingleton)。 A.h包含声明,而A.cpp具有定义。我需要在都被编译成不同DLL的B.cpp和C.cpp中使用此单例对象。 在B.cpp中,我想设置变量ptrval,在C.cpp中,我要检索变量ptrval。
在A.h
class MySingleton {
public:
static MySingleton* getInstance();
void setval(int* uid);
int* getval();
private:
MySingleton() = default;
~MySingleton() = default;
MySingleton(const MySingleton&) = delete;
MySingleton& operator=(const MySingleton&) = delete;
int* ptrval = nullptr;
static MySingleton* instance;
};
#ifdef MySingleton_DLLEXPORT
extern __declspec(dllexport) int* ptrval = nullptr;
extern __declspec(dllexport) MySingleton* getInstance();
extern __declspec(dllexport) void setval(int* uid);
extern __declspec(dllexport) int* getval();
extern __declspec(dllexport) MySingleton* instance = 0;
#else
extern __declspec(dllimport) int* ptrval;
extern __declspec(dllimport) MySingleton* getInstance();
extern __declspec(dllimport) void setval(int* uid);
extern __declspec(dllimport) int* getval();
extern __declspec(dllimport) MySingleton* instance;
#endif
在A.cpp中
#pragma push_macro("MySingleton_DLLEXPORT")
#define MySingleton_DLLEXPORT
#include <A.h>
#pragma pop_macro("MySingleton_DLLEXPORT")
MySingleton* MySingleton::instance;
MySingleton* MySingleton::getInstance()
{
if (instance == 0)
instance = new MySingleton();
return instance;
}
void MySingleton::setval(int* uid) {
this->ptrval = uid;
}
int* MySingleton::getval() {
return this->ptrval;
}
在B.cpp中
#pragma push_macro("MySingleton_DLLEXPORT")
#include <A.h>
#pragma pop_macro("MySingleton_DLLEXPORT")
int* uid = (getting uid from a function)
(MySingleton::getInstance())->setval(uid);
在C.cpp中
#pragma push_macro("MySingleton_DLLEXPORT")
#include <A.h>
#pragma pop_macro("MySingleton_DLLEXPORT")
ptrval = (MySingleton::getInstance())->getval();
我收到以下链接错误: B.obj:错误LNK2019:无法解析的外部符号“ public:静态类MySingleton * __cdecl MySingleton :: getInstance(void)”
任何帮助将不胜感激!