linux-C直接调用SO动态库和生成SO动态库的函数

 1 #include <stdio.h>   
 2 #include <dlfcn.h>   
 3   
 4 int main(void){   
 5    int (*myadd)(int a,int b);//fuction pointer   
 6    void *handle;   
 7       
 8    handle=dlopen("./libmyadd.so",RTLD_LAZY);//open lib file   
 9    myadd=dlsym(handle,"output");//call dlsym function   
10       
11   
12    int result=myadd(1,2);   
13    dlclose(handle);   
14    printf("%d\n",result);     
15 }  

以上为调用程序test8.c,

以下为库程序test7.c

1 int output(int a,int b){   
2    int x=a+b;   
3    return x;   
4 }  

 

gcc -shared -o libmyadd.so test7.c
gcc -ldl -o test8 test8.c
./test8
3

 

 

不管什么库文件,你都既要在包含.h文件(不然编译通不过:有未声明的函数),也要在gcc选项里面指定.so文件的位置(不然链接通不过:未知的符号) 比如 gcc -I include_path -L lib_path -lyourlib include_path改成你头文件的目录 lib_path改成你动态库文件的目录 -lyourlib 改成l加上你要引用的库文件名字 比如libpthread.so就改成-lpthread

 

源文地址:http://blog.163.com/laosan.../blog/static/401323332011585124980/

 

posted on 2015-11-24 21:33  咚..咚  阅读(854)  评论(0)    收藏  举报

导航