Chinaunix首页 | 论坛 | 博客
  • 博客访问: 368585
  • 博文数量: 62
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 557
  • 用 户 组: 普通用户
  • 注册时间: 2013-08-01 14:04
文章分类

全部博文(62)

文章存档

2014年(1)

2013年(61)

分类: C/C++

2013-12-19 14:57:59

原文地址:动态库的生成 _0303 作者:丫叩酱


点击(此处)折叠或打开

  1. #Makefile

  2. all:
  3.     gcc -shared -fPIC sub.c add.c -o libmath.so
  4.     gcc main.c -o main -ldl
  5. clean:
  6.     rm main libmath.so
  7. .PHONY:clean all

点击(此处)折叠或打开

  1. //add.c

  2. int add(int a, int b)
  3. {
  4.     return a + b;
  5. }

点击(此处)折叠或打开

  1. //sub.c

  2. int sub(int a, int b)
  3. {
  4.     return a - b;
  5. }

点击(此处)折叠或打开

  1. //main.c

  2. #include <stdio.h>
  3. #include "math.h"
  4. #include <dlfcn.h>
  5. #include <stdlib.h>

  6. typedef int (*funcp_t)(int, int);

  7. int main(void)
  8. {
  9.     void *handle;
  10.     funcp_t fun;

  11.     handle = dlopen("libmath.so", RTLD_NOW);
  12.     fun = dlsym(handle, "sub");

  13.     if(handle == NULL || fun == NULL)
  14.     {
  15.         printf("not find libmath.so\n");
  16.         exit(EXIT_FAILURE);
  17.     }

  18.     printf("sub: %d\n", fun(3, 5));

  19.     dlclose(handle);

  20.     return 0;
  21.     
  22. }

阅读(1878) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~