linux加载和链接动态共享库

17 篇文章 3 订阅

前言

动态库的加载
今天看到dlopen,dlsym的代码不知道在干什么,查阅了相关资料后大概整理了一下

linux接口

dlopen:以指定的模式打开动态库,这个相当于把符号表(函数名)加载到内存中,这样就可以使用动态库中已经有的函数名了;
dlsym:第一个参数时dlopen返回的句柄(可以简单的理解为智能指针),第二个参数为要查找的符号(函数名),若存在则返回的是函数地址,否则返回NULL,这样就可以使用函数调用了;
dclose:卸载当前加载的共享库;
dlerror:无参数,如果前面三个函数返回失败,则为错误消息,否则为NULL;

用途

微软Windows应用的开发者、大型游戏等常利用动态库来更新软件,这样用户只需要更新这个动态库文件就可以

代码解释

#include<math.h>

int add(int a, int b)
{
	return a+b;
}
int sub(int a, int b)
{
	return a-b;
}
int mul(int a, int b)
{
	return a*b;
}
int div(int a, int b)
{
	return a/b;
}

linux生成动态库的命令:gcc -shared -fpic math.c -o libmath.so

#include<stdio.h>
#include<math.h>
#include<dlfcn.h>

#define MATH_LIB_SO "./libmath.so"
typedef int (*math_pointer)(int, int);//定义函数指针

int main()
{
	int a=100, b=10;
	void * handle;
	math_pointer p;
	char *op[]={"add", "sub", "mul", "div"};
	
	//1、采用常规方法进行函数调用
	printf("%d %s %d = %d\n", a, op[0], b, add(a, b));
	printf("%d %s %d = %d\n", a, op[1], b, sub(a, b));
	printf("%d %s %d = %d\n", a, op[2], b, mul(a, b));
	printf("%d %s %d = %d\n", a, op[3], b, div(a, b));
	
	printf("*****************************************\n");
	
	//2、采用加载动态库的方法进行调用
	handle = dlopen(MATH_LIB_SO, RTLD_LAZY);
	if(handle == NULL)
	{
		printf("dlopen wrong\n");
		return 0;
	}
	for(int i=0; i<4; i++)
	{
		p = (math_pointer)dlsym(handle, op[i]);
		printf("%d %s %d = %d\n", a, op[i], b, p(a, b));
	}
	dlclose(handle);
	return 0;
}

linux动态链接共享库:gcc -rdynamic main.c math.c -ldl
由于main.c中有普通方式的调用,所以上述命令中需要显示的加上 math.c

#运行结果
100 add 10 = 110
100 sub 10 = 90
100 mul 10 = 1000
100 div 10 = 10
*****************************************
100 add 10 = 110
100 sub 10 = 90
100 mul 10 = 1000
100 div 10 = 10
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值