LINUX C语言:程序运行时动态加载库函数

PS:相关知识请自己去看man手册,这里只给出一个实例,及创建这个实例的步骤。


1:创建test.h, test.c文件

//test.h
#ifndef TEST_H_
#define TEST_H_

#include <stdio.h>

void PrintHello();
int Add(int a, int b);

#endif


//test.cpp
#include "test.h"

//输出文本hello, world
void Hello()
{
	printf("hello, world\n");
}

//返回两个参数的和
int Add(int a, int b)
{
	return a + b;
}


2:将其编译成动态库
gcc test.c -shared -fPIC -o libtest.so

3:创建主文件main.c

//main.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include <signal.h>
#include <errno.h>

//输出错误信息并退出      
void error_quit(const char *str)      
{      
	fprintf(stderr, "%s\n", str);   
	exit(1);      
}  

int main(int argc, char *argv [])
{
	void *plib;						//指向so文件的指针
	typedef void (*FUN_HELLO)();
	typedef int (*FUN_ADD)(int, int);
	FUN_HELLO funHello = NULL;		//函数指针
	FUN_ADD funAdd = NULL;

	//打开so文件
	//为了方便演示,我将库文件和可执行文件放在同一个目录下
	plib = dlopen("./libtest.so", RTLD_NOW | RTLD_GLOBAL);
	if( NULL == plib )
		error_quit("Can't open the libtest.so");

	//加载函数void Hello()
	funHello = dlsym(plib, "Hello");
	if( NULL == funHello )
		error_quit("Can't load function 'Hello'");
	
	//加载函数int Add(int a, int b)
	funAdd = dlsym(plib, "Add");
	if( NULL == funAdd )
		error_quit("Can't load function 'Add'");

	//调用成功加载的函数
	funHello();
	printf("5 + 8 = %d\n", funAdd(5, 8));

	//关闭so文件
	dlclose(plib);

	return 0;
}


4:编译,运行

gcc main.c -o main -ldl
./main

完成了,呵呵

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值