C++程序在运行时调用动态链接库,实现逻辑扩展,有两种基本链接方式:隐式链接和显式链接。下面就设立最基本情形实现上述链接。
创建DLL动态链接库
编辑头文件
mydll_3.h:
#pragma once
#define DLL_EXPORT_API extern "C" _declspec(dllexport)
//Function
DLL_EXPORT_API int Add(int a, int b);
//Class
class _declspec(dllexport) Math
{
public:
int Multiply(int a, int b);
};
stdafx.h:
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#include "targetver.h"
#define WIN32_LEAN_AND_MEAN // 从 Windows 头中排除极少使用的资料
// Windows 头文件:
#include <windows.h>
// TODO: 在此处引用程序需要的其他头文件
targetver.h:
#pragma once
// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。
// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将
// 将 _WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。
#include <SDKDDKVer.h>
编辑实现方法
mydll_3.cpp
// mydll_3.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "mydll_3.h"
int Add(int a, int b)
{
return a + b;
}
int Math::Multiply(int a, int b)
{
return a * b;
}
stdafx.cpp:
// stdafx.cpp : 只包括标准包含文件的源文件
// mydll_3.pch 将作为预编译标头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中引用任何所需的附加头文件,
//而不是在此文件中引用
检查配置
配置选择【动态库.dll】生成,即可得到对应动态链接库DLL和对应的静态链接库LIB。一般的,静态库包含函数的入口信息、类声明等信息,动态库中包含具体实现方法。
创建可执行文件EXE
接下来创建exe来调用链接库中的信息。
编辑头文件
stdafx.h:
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
// TODO: 在此处引用程序需要的其他头文件
targetver.h:
#pragma once
// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。
// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将
// 将 _WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。
#include <SDKDDKVer.h>
编辑实现方法
mytest_3.cpp:
// mytest_3.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "mydll_3.h"
#include "windows.h"
#pragma comment(lib,"mydll_3.lib") //意为告知编译器需要链接一个库,名叫 mydll_3.lib
//extern "C"_declspec(dllimport) int Add(int a, int b); //此处可有可无
// !!! 隐式链接 !!!
//TestDll.cpp
//void main()
//{
// int a;
// a = Add(8, 10);
// printf("结果为%d\n",a);
// Math m;
// printf("%d\n",m.Multiply(5, 3));
// system("pause");
//}
// !!! 显式链接(动态) !!!
void main(void)
{
typedef int(*pAdd)(int a, int b);
HINSTANCE hDLL;
pAdd Add;
hDLL = LoadLibrary(_T("mydll_3.dll"));//加载动态链接库MyDll.dll文件;
Add = (pAdd)GetProcAddress(hDLL, "Add");
int a = Add(5, 8);
printf("结果为%d\n",a);
FreeLibrary(hDLL);//卸载myDll.dll文件;
system("pause");
}
stdafx.cpp:
// stdafx.cpp : 只包括标准包含文件的源文件
// mytest_3.pch 将作为预编译标头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中引用任何所需的附加头文件,
//而不是在此文件中引用
检查配置
确保动态库DLL和对应静态库LIB在开发目录下,配置选择【应用程序.exe】,生成即可!如果要发布,将可执行文件exe和动态链接库dll一起拷贝至目标文件夹(静态库lib不需要随exe拷贝)。
小结
有些配置如果是用Visual Studio来开发的话能在其选项中具体设置,比较方便,比如专门有【链接器】配置等。显式链接比较灵活,只需dll动态链接库就可以实现,而隐式链接则稍麻烦(静态库和对应动态库都需要),但如果大量使用链接库中的函数、类,就有它的优势。其中的细节很多,另开篇幅再谈,感谢阅读!