1. 静态库
1.1 静态库的生成
mylib.cpp中的内容
int add(int a, int b)
{
return a + b;
}
1.2 静态库的使用
在代码里加上以下两句,然后配置库的路径
#pragma comment(lib, "myLib.lib")
extern int add(int a, int b);
法二:不用
pragma comment(lib, "myLib.lib")
的方式加载静态库,在属性页中的链接器上设置
2. 动态库
2.1 动态库的生成
mydll.cpp
//使用纯C的方式导出
extern "C" __declspec(dllexport) int add(int a, int b) {
return a + b;
}
//使用C++的方式导出 二者的函数名称不一样
__declspec(dllexport) int add2(int a, int b) {
return a + b;
}
2.2 动态库的使用
#include <iostream>
#include <string>
#pragma comment(lib, "mydll.lib")
extern "C" __declspec(dllimport) int add(int a, int b);
int main()
{
add(1, 2);
return 0;
}
2.3 动态库的使用 不加载静态库
#include <iostream>
#include <string>
#include <Windows.h>
int main()
{
HINSTANCE hDll = LoadLibrary(L"mydll.dll");
if (hDll == NULL)
{
std::cout << "load dll failed!";
return -1;
}
using functionPtr = int(*)(int, int);
functionPtr addFunction = (functionPtr)GetProcAddress(hDll, "add");
if (addFunction == NULL) {
std::cout << "connot find target function";
return -1;
}
std::cout << addFunction(1, 2);
return 0;
}
3. 常用的动态库的生成和使用方法
3.1动态库的生成
mydll.h
#pragma once
#ifndef DLL_IMPORT
#define API extern "C" __declspec(dllexport)
#else
#define API extern "C" __declspec(dllimport)
#endif
API int add(int a, int b);//函数的声明
mydll.cpp
#include "mydll.h"
//使用纯C的方式导出
API int add(int a, int b) {
return a + b;
}
3.2动态库的使用
配置静态库路径
#define DLL_IMPORT //定义宏
#include <iostream>
#include <string>
#include <Windows.h>
#include "../dongtaiku/mydll.h"
#pragma comment(lib, "mydll.lib")//加载静态库,dll放在exe的运行路径
int main()
{
std::cout << add(1, 2);
return 0;
}
4. 导出类
类不能直接被导出
4.1 导出法1
mydll.h
#pragma once
#ifndef DLL_IMPORT
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif
class API ExportClass {
public:
int add(int a, int b);
};
mydll.cpp
#include "mydll.h"
int ExportClass::add(int a, int b)
{
return a + b;
}
main.cpp
#include <iostream>
#include "../../ExprotClassDll/ExprotClassDll/mydll.h"
#pragma comment(lib, "ExprotClassDll.lib")
int main() {
ExportClass instance;
std::cout << instance.add(1, 2);
return 0;
}