在windows环境DLL链接问题之一中,简要了讲述了Dllimport的问题,但是贴在其中的代码还没有详细解释,现在就来看一下吧!
为了解释C/C++修饰符的问题,简单了写了个测试文件,用来测试DLL文件的功能。代码如:
// DllCommain.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "../DllCom/DllCom.h"
#pragma comment(lib,"..\\Test\\Debug\\DllCom.lib")
int _tmain(int argc, _TCHAR* argv[])
{
#ifdef __cplusplus
printf("main c++ definition!\n");
#else
printf("main c++ not definition!\n");
#endif
printf("%s\n",GetValueString(0));
SetValueString("hello big WORLD!");
printf("%s\n",GetValueString(0));
getchar();
return 0;
}
1. __cdecl修饰符
C/C++调用默认的修饰符,也就是说:如果你写了形如 int read(); 这样的函数,也就等于 int __cdecl read(); 当编译器根据源文件的内容生成.obj文件时,
read这个函数名就会按照_cdecl的调用约定更改。
在
windows环境DLL链接问题之
一中,我们首先编译生成DLL文件和lib文件,由于VS编译器是按照扩展名来识别源文件的,因此这些文件都被看做为C++源文件
,这样
__cplusplus
也就处于定义状态。
这样我们就告诉编译器,虽然是C++源文件,但是我们希望它按照C文件的规则(extern "C"的作用)生成函数修饰符。
使用VS提供的Dependency工具查看Dll文件的输出函数列表:
使用dumpbin.exe文件查看DllCommain.cpp生成的DllCommain.obj文件:
我们在看一看DllCommain.exe的内容:
DllCommain.exe确实输入了DllCom.dll中的这两个函数,而且经过修饰的名称就是原来的函数名。这就是extern "C"和__cdecl结合的作用了!
现在我们去掉extern “C”这个修饰,再来看看输出有什么不同???
为了简便,将Dllcom.h文件和DllCom.cpp文件中
#ifdef
__cplusplus
改成
#ifndef__cplusplus
看看现在DLLcom.dll中的输出:
DllCommain。obj文件的内容:
直接查看DllCommain.exe文件的内容:
这就是C++编译器对C++源代码的默认修饰结果了。
如果你的调用DLL中函数的链接出现错误,如unresolved external symbol "void __cdecl SetValueString(char const *)"
(?SetValueString@@YAXPBD@Z) referenced in function _wmain,这
句错误是由于我重新编译了使用extern "C"的DLL文件,
导致main函数在编译时生成的
修饰符
?SetValueString@@YAXPBD@Z在DLL文件中找不到!