【c++随笔】MinGW32编译环境实现DLL的创建与调用实例

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.cppcal.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位兼容性问题

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值