在编译两个类时,我收到了LNK4217警告:其中一个定义了一个抽象接口和一个静态工厂方法,将返回实现此接口的对象。此类通过`__declspec(dllexport)`导出。另一个类实现了该接口。以下是可复现警告的简化示例:
PublicAPI.h
PublicAPI.h
#pragma once
#include <memory>
#ifdef PublicAPI_Exports
#define API_EXP __declspec (dllexport)
#else
#define API_EXP __declspec (dllimport)
#endif
class API_EXP PublicAPI
{
public:
virtual ~PublicAPI();
static std::shared_ptr<PublicAPI> init(const char *selection);
virtual int compute() = 0;
protected:
PublicAPI();
};
PublicAPI.cpp
#include "PublicAPI.h"
#include "../PrivateAPI/PrivateAPI.h"
PublicAPI::PublicAPI() {}
PublicAPI::~PublicAPI() {}
std::shared_ptr<PublicAPI> PublicAPI::init(const char *selection)
{
return std::make_shared<PrivateAPI>(selection);
}
PrivateAPI.h
#pragma once
#include "../PublicAPI/PublicAPI.h"
#include <memory>
#include <string>
class PrivateAPI : public PublicAPI
{
public:
PrivateAPI(std::string selection);
virtual ~PrivateAPI();
virtual int compute();
private:
PrivateAPI();
// should have more private members here, avoided to shorten the example
};
PrivateAPI.cpp
#include "PrivateAPI.h"
PrivateAPI::PrivateAPI() {}
PrivateAPI::PrivateAPI(std::string selection)
{
// init members based on selection
}
PrivateAPI::~PrivateAPI() {}
int PrivateAPI::compute()
{
return 42;
}
PrivateAPI
被编译成静态库,PublicAPI
被编译成DLL,并链接到PrivateAPI
。 PublicAPI_Exports
在PublicAPI
项目中定义。
我收到的警告如下:
3>PrivateAPI.lib(PrivateAPI.obj) : warning LNK4217: locally defined symbol ??1PublicAPI@@UEAA@XZ (public: virtual __cdecl PublicAPI::~PublicAPI(void)) imported in function "public: virtual __cdecl PrivateAPI::~PrivateAPI(void)" (??1PrivateAPI@@UEAA@XZ)
3>PrivateAPI.lib(PrivateAPI.obj) : warning LNK4217: locally defined symbol ??0PublicAPI@@IEAA@XZ (protected: __cdecl PublicAPI::PublicAPI(void)) imported in function "private: __cdecl PrivateAPI::PrivateAPI(void)" (??0PrivateAPI@@AEAA@XZ)
我阅读了关于此链接器警告的Microsoft Docs和StackOverflow,但我仍然不知道出了什么问题,或者如何正确修复它 :/