Linux C动态链接库实现一个插件例子
2024-08-30 05:30:55
实现一个简单的计算动态链接库;升级动态链接库后,在不重新编译主程序的情况下,直接生效。
lib库:
#cat math.c
#include <stdio.h>
int add(int x, int y)
{
return (x + y);
}
int sub(int x, int y)
{
return (x - y);
}
int mul(int x, int y)
{
return (x * y);
}
int div(int x, int y)
{
return (x/y);
}
生成动态链接库
#gcc -shared -fPIC -o libmath.so math.c
主程序:
#cat main.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
typedef int (*cac_func)(int, int);
int main(void)
{
void *handle;
char *error;
cac_func fp=NULL;
handle = dlopen("./libmath.so", RTLD_LAZY);
if (!handle)
{
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
dlerror();
fp = dlsym(handle, "add");
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%s\n", error);
exit(EXIT_FAILURE);
}
printf("add:%d\n", fp(1,1));
return 0;
}
#gcc -o main.out main.c
/tmp/ccTdLhjj.o: In function `main':
main.c:(.text+0x1b): undefined reference to `dlopen'
main.c:(.text+0x2b): undefined reference to `dlerror'
main.c:(.text+0x56): undefined reference to `dlerror'
main.c:(.text+0x67): undefined reference to `dlsym'
main.c:(.text+0x70): undefined reference to `dlerror'
collect2: error: ld returned 1 exit status
需要使用 指定使用动态链接库: dl
#gcc -o main.out -ldl main.c
运行:
#./main.out
add:2
修改库:
#cat math.c
#include <stdio.h>
int add(int x, int y)
{
return (x + y + 100);
}
重新编译库:
#gcc -shared -fPIC -o libmath.so math.c
运行:
#./main.out
add:102
最新文章
- 注释生成Api文档
- [转]socket 通俗解释
- Spark&;Hive:如何使用scala开发spark访问hive作业,如何使用yarn resourcemanager。
- css常用代码
- 在Swift中应用Grand Central Dispatch(上)转载自的goldenfiredo001的博客
- The L1 Median (Weber 1909)
- Zabbix Api的使用
- asp.net Hierarchical Data
- win2003 sp2+iis 6.0上部署.net 2.0和.net 4.0网站的方法
- Ext JS学习第十七天 事件机制event(二)
- 与众不同 windows phone (13) - Background Task(后台任务)之后台文件传输(上传和下载)
- drag
- EF Unit Of Work
- SQL SERVER:CASE判断空,错误一例
- 初识QT
- ●POJ 3348 Cows
- Python包中 __init__.py文件的作用
- Spring AOP中的JDK和CGLib动态代理哪个效率更高?
- Ubuntu16.04安装NVIDIA显卡驱动
- JVM Internals