设为首页 加入收藏

TOP

Linux C语言:程序运行时动态加载库函数
2014-11-24 08:27:22 来源: 作者: 【 】 浏览:1
Tags:Linux 语言 程序 行时 动态 加载 函数

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


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


//test.h
#ifndef TEST_H_
#define TEST_H_


#include


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


#endif


2:将其编译成动态库


gcc test.c -shared -fPIC -o libtest.so


3:创建主文件main.c


//main.c
#include
#include
#include
#include
#include


//输出错误信息并退出
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


完成了,呵呵


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇UNIX Shell控制结构—IF 下一篇C++:在程序中获取全球唯一标识号..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·如何从内核协议栈到 (2025-12-27 03:19:09)
·什么是网络协议?有哪 (2025-12-27 03:19:06)
·TCP/ IP协议有哪些 (2025-12-27 03:19:03)
·怎样用 Python 写一 (2025-12-27 02:49:19)
·如何学习python数据 (2025-12-27 02:49:16)