动态链接库的生成与使用(动态、静态调用)附上一种常见错误。。。
本篇内容总结了动态链接库的生成与使用。
一.动态链DLL接库生成
- 首先,新建Win32 DLL 空项目
- 添加头文件和源文件,这里写一个printMAX作为测试
//myDll.h
#pragma once
extern "C" _declspec(dllexport) int printMax(int, int);
//myDll.cpp
#include<iostream>
using std::cout ;
using std::endl;
extern "C" _declspec(dllexport)
int printMax(int a, int b)
{
cout << "the max number is: " << ((a>b) ? a : b) << endl;
return 0;
}
头文件和源文件添加完成后,运行,可以看到,已经生成了myDll.dll
此时也可以看到目标debug目录下面生成dll和lib文件,如果只有dll,而没有lib,大概率是出现了这个问题;
二.动态链DLL测试
在解决方案上右键,添加新项目myDllTest,作为测试dll的项目,右键设为启动项目
- 动态库的动态调用
动态调用dll,只需要一个dll文件即可,首先使用LoadLibrary,加载动态库,然后使用GetProcAddress,得到函数的地址;
#include<Windows.h>
#include<iostream>
using namespace std;
int main()
{
//加载dll
HMODULE module = LoadLibrary(TEXT("..\\Debug\\myDll.dll"));
if (module == NULL)
{
cout << "load dll error!" << endl;
FreeLibrary(module);
return 1;
}
//从dll中导出函数地址
typedef void(*printMaxFunc)(int, int); // 定义函数指针类型
printMaxFunc printMax;
printMax = (printMaxFunc)GetProcAddress(module, "printMax");
GetLastError();
if (printMax == NULL)
{
cout << "get dll error!" << endl;
FreeLibrary(module);
return 1;
}
//测试dll
int c = 3;
int d = 2;
printMax(c, d);
//释放
FreeLibrary(module);//与LoadLibrary成对出现,颇有new delete的意思
return 0;
}
- 动态库的静态调用
动态库的静态调用,需要dll lib h文件。
同样在解决方案上右键新建项目myDllTest2,作为测试静态调用的工程,右键设为启动文件。
首先需要自己把myAdd.h文件人为添加到文件夹myDllTest2里面,然后新建测试cpp文件
#include<iostream>
#include"myAdd.h"
using namespace std;
#pragma comment (lib,"..\\Debug\\myDll.lib")
int main()
{
int c = 3;
int d = 2;
printMax(c, d);
return 0;
}
附上我的完整工程,可下载使用,采用vs2015
CSDN博客搬运 文章被收录于专栏
CSDN博客搬运