LINUX C语言:程序运行时动态加载库函数
2013-02-02 11:12
603 查看
PS:相关知识请自己去看man手册,这里只给出一个实例,及创建这个实例的步骤。
1:创建test.h, test.c文件
2:将其编译成动态库
3:创建主文件main.c
4:编译,运行
完成了,呵呵
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
完成了,呵呵
相关文章推荐
- Linux C语言:程序运行时动态加载库函数
- Linux c语言程序运行时动态加载库函数
- C语言中内存分布及程序运行加载过程
- linux动态链接库中函数的运行时加载
- Android中插件开发篇之----动态加载Activity(免安装运行程序)
- 在Linux下用C语言写一个小程序实现一个进度条编写Makefile来进行运行
- linux替换运行程序或so动态库文件导致的问题
- Linux下程序的加载、运行和终止流程 .
- gm8180:arm linux启动加载模块、运行程序
- Android中插件开发篇之----动态加载Activity(免安装运行程序)
- Linux 可执行文件 ELF结构 及程序加载运行
- Linux下用C语言判断程序是否已运行
- linux下由于线程局部存储未初始化导致加载动态链接库时程序崩溃的BUG
- linux下运行自己编写的C语言程序提示bash:./*** 权限不够
- Linux程序运行时找不到动态链接库的原因
- [转] Linux下程序的加载、运行和终止流程
- linux程序运行时加载共享库出现的错误
- Android中插件开发篇之----动态加载Activity(免安装运行程序)
- linux运行程序时,出现加载动态库失败:Cannot restore segment prot after reloc: Permission denied
- [LinuxC]加载动态链接库so程序简单实例