错误 LNK2019:将代码放入 cpp 文件时无法解析的外部符号

error LNK2019: unresolved external symbol when put code into cpp file

我在 .h 文件中定义了一个静态成员函数,它工作正常。

当我尝试将实现移动到 .cpp 文件时,项目构建失败并出现 LNK2019 错误,另一个 class 正在调用此函数。

错误信息是:

8>------ Build started: Project: COrders, Configuration: Debug x64 ------
8>     Creating library D:\devel\Server\COrders\Debugx64\COrders.lib and object D:\devel\Server\COrders\Debugx64\COrders.exp
8>OrderProcessor.obj : error LNK2019: unresolved external symbol "public: static bool __cdecl COAValidator::ValidatePercentage(class CSDO const &,class CExecInstHelper const &,class ATL::CStringT<char,class StrTraitMFC_DLL<char,class ATL::ChTraitsCRT<char> > > const &)" (?ValidatePercentageXI@COAValidator@CPlus@@SA_NAEBVCSDO@AEBVCExecInstHelper@@AEBV?$CStringT@DV?$StrTraitMFC_DLL@DV?$ChTraitsCRT@D@ATL@@@@@ATL@@@Z) referenced in function "private: int __cdecl CPlus::COrderProcessor::DoCreate(int)" (?DoCreate@COrderProcessor@CPlus@@AEAAHH@Z)
8>D:\devel\Server\Server\COrders\Debugx64\COrdersd.dll : fatal error LNK1120: 1 unresolved externals

此处 COrderProcessor::DoCreate() 正在尝试调用 static bool COAValidator::ValidatePercentage(),它通过 .dll

提供

知道如何解决吗?

当您在 .h 文件中完全定义此函数时,它会被编译到 #include 属于 .h 文件的任何客户端代码中,并且不需要链接来定位函数定义。

但是,如果将函数定义移动到 .cpp 文件,客户端代码在编译时将无法再看到该定义,而是依赖链接器来定位它。然后必须将该函数标记为 dllexport,以便它包含在 dll 的函数 table.

此页面描述了执行此操作的语法:https://msdn.microsoft.com/en-us/library/a90k134d.aspx