您的位置:首页 > 运维架构 > Linux

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

2017-09-25 14:55 344 查看
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
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
完成了,呵呵
文章出自:http://www.linuxidc.com/Linux/2013-02/78935.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Linux 动态 加载机制