在静态方法中使用函数时,会出现LNK2019未解析的外部

时间:2015-04-09 14:05:43

标签: c++ visual-studio

我有一个C ++ Visual Studio 2013控制台应用程序,它应该使用我编写的DLL MyDLLlib.dll。 MyDLLlib是用C语言编写的。其中一个函数叫做Get_Version。原型是

const char *Get_Version();

我把它放在源文件的顶部以使用原型:

extern "C"{
#include "MyDLLlib.h"
}

如果在函数中调用main作为此

printf("version %s\n",Get_Version());

然后它有效。

但是,如果我添加一个带有一些静态方法的类,并且静态方法调用Get_Version()

const char * ret = Get_Version();

然后我收到链接错误:

Error   1   error LNK2019: unresolved external symbol 
"__declspec(dllimport) char * __cdecl Get_Version(void)" (__imp_?Get_Version@@YAPADXZ) 
referenced in function "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl ServiceDispatch::decoder_Get_Version(class StringBuffer &)" 
(?decoder_Get_Version@ServiceDispatch@@CA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@AAVStringBuffer@@@Z)   
D:\devt\CplusPlus\VSTrials\Link_to_MyDLLlib\Link_to_MyDllLib\ServiceDispatch.obj    Link_to_MyDLLlib``

我使用相同的include。

关于我可能做错什么的任何线索?

1 个答案:

答案 0 :(得分:1)

如果CLASS_DECLSPEC定义始终__declspec(dllimport),则无法确定。看看这个样本:

<强> DLL_header.h

#if defined( _BUILD_DLL )
#   define DLLAPI           __declspec(dllexport) //Export when building DLL
#else
#   define DLLAPI           __declspec(dllimport) //Import when using in other project
#endif

DLLAPI const char *Get_Version();

<强> DLL_source.cpp

#include "Header.h"

const char *Get_Version()
{
    return "1.1.0.4";
}

构建定义了_BUILD_DLL的DLL。

<强> Main.cpp的

#include "DLL_header.h"

int main()
{
    printf("%s\n", Get_Version());
    return 0;
}

构建此内容,_BUILD_DLL 未定义

在您的情况下,extern "C"可能会出现问题 - 您在extern "C"中包含标头,该标头将Get_Version()声明为__cdecl链接。但链接器正在搜索

__imp_?Get_Version@@YAPADXZ

这是一个受损的(C ++)名称。你的DLL是C或C ++项目吗?如果您的DLL构建为C项目(而不是C++),请将extern "C"放在Get_Version()的声明#ifdef上:

#ifdef __cplusplus
extern "C" {
#endif

DLLAPI const char *Get_Version();

#ifdef __cplusplus
}
#endif

无论哪种方式,请从extern "C"周围移除#include。另外,检查此DLL的.lib文件是否作为依赖项附加到项目。

相关问题