您的位置:首页 > 运维架构 > Linux

linux下动态链接问题(.so文件的编写与调用)

2008-09-27 21:39 573 查看
实例:deposit.c save.c dig.h dy.c 这是一个及其简陋的银行界面(姑且这么说吧)

1.(deposit.c文件,取款)
#include "dig.h"

void deposit(){
printf("you deposit 5000$ /n");
}
2.(save.c文件,存款)
#include "dig.h"

void save(){
printf("you saved 1000$ /n");
}
3.(dig.h文件)
#ifndef _DIG_H
#define _DIG_H

#ifdef SHARED
void (*save)();
#else
void save();
#endif

#ifdef SHARED
void (*deposit)();
#else
void deposit();
#endif

#endif

4.(dy.c主函数调用两项功能)
#include <stdio.h>
#include <dlfcn.h>
#define SOFILE "./my.so"
#define SHARED
#include "dig.h"

main(){
void *dp;
char *error;
void (*func)();
while(1){
/*以下为调用.so文件,用到了函数dlopen8/
dp =dlopen(SOFILE,RTLD_LAZY);//打开.so文件,RTLD_LAZY为参数
if(dp==NULL){
fputs(dlerror(),stderr);
exit(1);
}
showGUI();
char s[10];
scanf("%s",&s);
func = dlsym(dp,s);//把输入的字符串s与.so文件中的文件名匹配,看是否能找到此函数
error = dlerror();
if(error){
fputs(error,stderr);
exit(1);
}
(*func)();//找到了此函数如输入的是 save 则在此调用save函数
continue;
}
dlclose(dp);
exit(0);
}
int showGUI(){
FILE *login;
char c;
login = fopen("login.txt","r");
if(!login){
printf("file err:login/n");
return;
}
while(1){
c = fgetc(login);
if(c == EOF){
break;
}
printf("%c",c);
}
fclose(login);
return 0;
}

编译过程:
1.编译得到my.so文件
gcc save.c deposit.c -fPIC -shared -o my.so

2.编译生成执行文件 dy
gcc dy.c -L. -lmy -o dy

详细说明:
-fPIC:表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的,所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正的代码段共享的目的
-L. :表示要连接的库在当前的目录中
-lmy:编译器查找动态链接库时有隐含的命名规则,即在给出的名字前面加上lib,后面加上.so来确定库的名字
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: