今天同學問了個問題, 爲什麼包含了<dlfcn.h> 用dlopen 還提醒未定義
我拿源碼來看了下
#include <stdlib.h>
#include <dlfcn.h>
#include "add.h"
#include <stdio.h>
typedef int(*P_FUNC)(int,int);
int main(){
void *handler = dlopen("libtext.so",RTLD_NOW);
P_FUNC add = dlsym(handler,"add");
P_FUNC sub = dlsym(handler,"sub");
//if(!sub) perror("sub dlsym"),exit(-1);
P_FUNC mul = dlsym(handler,"mul");
//if(!mul) perror("mul dlsym"),exit(-1);
show(30,'+',20);
printf("%d\n",add(30,20));
show(30,'-',20);
printf("%d\n",sub(30,20));
show(30,'*',20);
printf("%d\n",mul(30,20));
dlclose(handler);
return 0;
}
更改如下
typedef int(*P_FUNC)(int,int);
typedef void (*P_SHOW)(int,char,int); //new
int main(){
void *handler = dlopen("libtext.so",RTLD_NOW);if(!handler) perror("dlopen"),exit(-1);
P_FUNC add = (P_FUNC)dlsym(handler,"add");
if(!add) perror("add dlsym"),exit(-1);
P_FUNC sub = (P_FUNC)dlsym(handler,"sub");
if(!sub) perror("sub dlsym"),exit(-1);
P_FUNC mul = (P_FUNC)dlsym(handler,"mul");
if(!mul) perror("mul dlsym"),exit(-1);
P_SHOW show = (P_SHOW)dlsym(handler,"show"); //new
//if(!show) perror("show dlsym"),exit(-1);
show(30,'+',20);
printf("%d\n",add(30,20));
show(30,'-',20);
printf("%d\n",sub(30,20));
show(30,'*',20);
printf("%d\n",mul(30,20));
dlclose(handler);
return 0;
}
接下來 繼續編譯 gcc main.c -ldl 沒想到遇到了段錯誤, 並且終端輸出了 dlopen: Success
if (!handler) {
printf ("dlopen失敗:%s\n", dlerror());
return -1;
}
編譯 結果輸出的是
dlopenʧ�ܣ�libtext.so: cannot open shared object file: No such file or directory
打開動態庫失敗............果斷忘了配置環境變量.............但是可以肯定的是 perror() 不能 代替dlerror()功能 ,稍後套路他倆的區別,先導入環境變量
$export LIBRARY_PATH=$LIBRARY_PATH:.
$export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.
編譯 運行 成功.
接下來我去查了 perror() 和 dlerror()的區別.
原來對動態鏈接庫有特定的dlerror函數返回錯誤信息.
函數描述: