我有一个C++Visual Studio 2013控制台应用程序,它应该使用我编写的DLL MyDLLlib.DLL。MyDLLlib是用C编写的。其中一个函数名为Get_Version。原型是
const char *Get_Version();
我把这个放在源文件的顶部,以利用原型:
extern "C"{
#include "MyDLLlib.h"
}
如果在函数中被调用作为这个
printf("version %sn",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:devtCplusPlusVSTrialsLink_to_MyDLLlibLink_to_MyDllLibServiceDispatch.obj Link_to_MyDLLlib``
我正在使用相同的include。
有没有线索表明我可能做错了什么?
如果将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("%sn", Get_Version());
return 0;
}
在未定义_BUILD_DLL
的情况下构建此。
在您的情况下,extern "C"
可能有问题——您在extern "C"
中包含标头,它声明Get_Version()
具有__cdecl
链接。但链接器正在搜索
__imp_?Get_Version@@YAPADXZ
这是一个损坏的(C++)名称。你的DLL是C还是C++项目?如果您的DLL是作为C
项目(而不是C++
)构建的,请使用以下#ifdef
:将extern "C"
放在Get_Version()
的声明中
#ifdef __cplusplus
extern "C" {
#endif
DLLAPI const char *Get_Version();
#ifdef __cplusplus
}
#endif
无论哪种方式,都可以从#include
周围移除extern "C"
。此外,请检查此DLL的.lib
文件是否作为依赖项附加到项目。