实现一个简单的计算动态链接库;升级动态链接库后,在不重新编译主程序的情况下,直接生效。

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

最新文章

  1. 注释生成Api文档
  2. [转]socket 通俗解释
  3. Spark&amp;Hive:如何使用scala开发spark访问hive作业,如何使用yarn resourcemanager。
  4. css常用代码
  5. 在Swift中应用Grand Central Dispatch(上)转载自的goldenfiredo001的博客
  6. The L1 Median (Weber 1909)
  7. Zabbix Api的使用
  8. asp.net Hierarchical Data
  9. win2003 sp2+iis 6.0上部署.net 2.0和.net 4.0网站的方法
  10. Ext JS学习第十七天 事件机制event(二)
  11. 与众不同 windows phone (13) - Background Task(后台任务)之后台文件传输(上传和下载)
  12. drag
  13. EF Unit Of Work
  14. SQL SERVER:CASE判断空,错误一例
  15. 初识QT
  16. ●POJ 3348 Cows
  17. Python包中 __init__.py文件的作用
  18. Spring AOP中的JDK和CGLib动态代理哪个效率更高?
  19. Ubuntu16.04安装NVIDIA显卡驱动
  20. JVM Internals

热门文章

  1. Django缓存系统选择之Memcached与Redis的区别与性能对比
  2. WEB开发框架系列教程 (三)页面功能开发(2)
  3. 【189】◀▶ PowerShell 系统学习
  4. HDU2604:Queuing(矩阵快速幂+递推)
  5. Python Flask 实现移动端应用接口(API)
  6. maven-将依赖的 jar包一起打包到项目 jar 包中
  7. [SHOI2002]取石子游戏之三
  8. Lightoj 1054 - Efficient Pseudo Code
  9. 51nod 1154 回文串划分
  10. QT5每日一学(三) QT登陆对话框