linux 动态链接的使用

来源:互联网 发布:type c数据接口 编辑:程序博客网 时间:2024/06/01 11:53

动态链接

动态链接可以用来更新,特别是在服务器开发和现在很多的移动应用开发,使用动态链接库使代码不依赖于固定的版本,使用动态链接共享库可以让应用来动态的加载,在linux下的动态共享库是.so文,下面是具体的生成方法以及使用方法:

1、编写共享库代码(template.c):

/***共享库的内容*/
</pre><pre name="code" class="cpp">#include<stdio.h>void max(const int x,const int y){int m=x>y?x:y;printf("MAX=%d\n",m);}void min(const int x,const int y){int m=x<y?x:y;printf("MIN=%d\n",m);}void average(const int x,const int y){float avg=(x+y)/2;printf("avg=%f\n",avg);}void sort(int *p,const int n){int i;i=0;for(i=0; i<n; ++i){    int j;    for(j=0; j<n-i; ++j)if(p[j]>p[j+1]){   int temp=p[j];   p[j]=p[j+1];           p[j+1]=temp;}}}

2、生成共享库.so文件(template.so):

使用shell命令:

shell:~$ gcc  -shared  -fPIC  -o  template.so  template.c

这样就生成了共享库文件

3、编写程序以及应用共享库,(程序文件template_test.c):

/***.so使用的地方**只要知道共享库里面的内容我们就能使用它们***/#include<stdio.h>#include<dlfcn.h>#include<stdlib.h>#include<errno.h>int main(int argc,const char *argv[]){if(argc<=1){   printf("please so file\n");   return 1;}void *handle;/***下面就是共享库里面有的内容,我们就可以使用这来操作共享库中的操作了**也就是我们可以返回共享库里面操作的接口,下面的就是用来存放接口的地方*/void (*max)(int ,int);void (*min)(int ,int);void (*average)(int,int);void (*sort)(int *,const int n);//下面是打开共享库//handle=dlopen(argv[1],RTLD_LAZY);if(!handle){   printf("dlopen fail!%s  %s\n",strerror(errno),handle);   return 1;}//下面是返回共享库的接口//max=dlsym(handle,"max");min=dlsym(handle,"min");average=dlsym(handle,"average");sort=dlsym(handle,"sort");char *error; error=dlerror();if(error!=NULL){  printf("dlerror:%s\n",error);  exit(1);}int x;int y;x=10;y=20;//下面是使用接口//max(x,y);min(x,y);average(x,y);int data[5]={3,2,5,4,1};sort(data,5);int i=0;for(i=0; i<5; ++i)    printf("%d   ",data[i]);printf("\n");return 0;}这样就完成了程序的编写以及共享库的应用4、编译程序,(template_test):
shell:~$  gcc   -o1   -o  template_test    template_test.c   -ldl这样就生成了程序.o文件,在编译的过程中   -ldl  是必须的,否则对于链接共享库是错误的5、运行程序:
shell:~$ ./template_test   /home/shockerjue/test/template.so6、运行结果是:
MAX=20MIN=10avg=15.0000001   2   3   4   5 

	
				
		
原创粉丝点击