g++实现DLL的打包和引用
-
实现cpp代码的打包
- 编写接口函数 cal.cpp
#define BUILD_CAL_DLL // 定义xxx.dll构建 #include "cal.h" // 引用xxx.h头文件 /*接口函数*/ int addInt(int a, int b){ return a + b; } int subInt(int a, int b){ return a - b; }
- 编写头文件 cal.h
#ifdef BUILD_CAL_DLL // 如果定义了构建,表示生成xxx.dll #define EXPORT __declspec(dllexport) #else // 否则表示引用xxx.dll #define EXPORT __declspec(dllimport) #endif /*接口*/ extern "C"{ EXPORT int addInt(int, int); EXPORT int subInt(int, int); }
- 编译生成xxx.dll
g++ -shared -Wl,--kill-at,--output-def,cal.def,--out-implib,cal.a -o cal.dll cal.cpp
静态引用方式 >> #pragma comment(lib, “cal.a”),尚不会使用,cal.a, cal.ref 的使用方法请自行分析
-
实现dll文件的两种引用
声明: 此处默认main.cpp与cal.dll在同一目录下
- 隐式链接(常用)
/*main.cpp*/ #include <iostream> #include "cal.h" using namespace std; int main(int argc, char const *argv[]) { /* code */ cout << addInt(5, 6) << endl; cout << subInt(9, 4) << endl; return 0; }
编译: g++ cal.dll main.cpp -o main
- 显式链接
/*main.cpp*/ #include <iostream> #include <windows.h> using namespace std; int main(int argc, char const *argv[]) { /* code */ // windows.h 中的加载器 HINSTANCE Hdll; Hdll = LoadLibrary("cal.dll"); if(!Hdll){ FreeLibrary(Hdll); cout << "Error!" << endl; return 0; } // 定义函数变量 typedef int(*ADDINT)(int a, int b); typedef int(*SUBINT)(int a, int b); ADDINT addInt = (ADDINT)GetProcAddress(Hdll,"addInt"); SUBINT subInt = (SUBINT)GetProcAddress(Hdll,"subInt"); cout << addInt(5, 6) << endl; cout << subInt(9, 4) << endl; FreeLibrary(Hdll); return 0; }
编译: g++ main.cpp -o main
- 注:这样生成dll文件的可能缺陷:
不同的编译环境下32位和64位兼容性问题