我开始研究带有隐式链接的 DLL。我真的不完全理解它是如何工作的。请纠正我错误的地方。 我未能编译下一个代码(3 个模块):
MyLib.h
#ifdef MYLIBAPI
#else
#define MYLIBAPI extern "C" __declspec(dllimport)
#endif
MYLIBAPI int g_nResult;
MYLIBAPI int Add(int nLeft, int nRight);
据我了解,这是 DLL 的 header 。 #define MYLIBAPI extern "C"__declspec(dllimport)
意味着我们将在此处声明一些函数/变量,这些函数/变量将在专门的 .cpp 文件中进行描述,并将包含在 DLL 中。
MyLibFile1.cpp
#include <windows.h>
#define MYLIBAPI extern "C" __declspec(dllexport)
#include "MyLib.h"
int g_nResult;
int Add(int nLeft, int nRight) {
g_nResult = nLeft + nRight;
return(g_nResult);
}
所以,这显然是实现我们功能的文件。这是 DLL 的一部分,对吧?
MyExeFile1.cpp
#include <windows.h>
#include <strsafe.h>
#include <stdlib.h>
#include "MyLib.h"
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int) {
int nLeft = 10, nRight = 25;
TCHAR sz[100];
StringCchPrintf(sz, _countof(sz), TEXT("%d + %d = %d"),
nLeft, nRight, Add(nLeft, nRight));
MessageBox(NULL, sz, TEXT("Calculation"), MB_OK);
StringCchPrintf(sz, _countof(sz),
TEXT("The result from the last Add is: %d"), g_nResult);
MessageBox(NULL, sz, TEXT("Last Result"), MB_OK);
return(0);
}
所以,这是我们使用库中函数的可执行文件。 整件事都行不通。我试图将它们全部放入一个目录中并立即编译。我首先尝试从前两个模块(成功)编译一个 DLL,然后编译可执行文件(更改头文件的路径)。然而,它两次都导致了 2 个错误:
错误 LNK2019:未解析的外部符号 _WinMain@16 在函数 ___tmainCRTStartup 中引用
\Visual Studio 2008\Projects\MyExeFile1\Debug\MyExeFile1.exe : fatal error LNK1120: 1 个 Unresolved external 问题
这样做的正确方法是什么 - 我应该在代码中更改什么以及我应该如何编译代码(我使用 VS2008)? 谢谢。
最佳答案
#include <tchar.h>
解决链接器错误。
你的头文件应该是这样的:
#ifdef BUILDING_DLL
# define MYLIBAPI extern "C" __declspec(dllexport)
#else
# define MYLIBAPI extern "C" __declspec(dllimport)
#endif
MYLIBAPI int __stdcall Add(int nLeft, int nRight);
在“解决方案资源管理器”、“属性”、“C/C++”、“预处理器”、“预处理器定义”中右键单击您的 DLL 项目,添加“BUILDING_DLL”。重复发布配置。
您可以使用 Dumpbin.exe/exports 验证您的 DLL 是否正确导出函数。
__declspec(dllimport) 声明符不是绝对必要的,但它确实使它更有效率。 __stdcall 属性也不是必需的,但是它确实使您的 DLL 可用于任何支持调用 DLL 导出的语言。
关于c++ - 隐式链接 DLL 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2077664/