日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux 动态链接库的创建和使用--动态连接

發布時間:2025/3/15 linux 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux 动态链接库的创建和使用--动态连接 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

linux 動態鏈接庫的創建和使用--動態連接

分類: C 編程 568人閱讀 評論(0) 收藏 舉報 linuxreferencefunctiondatec /*
?* author: hjjdebug
?* date: 2012
?* title: linux 動態鏈接庫的創建和使用--動態連接
*/

動態連接,就是由調用者顯式調用指定庫,并獲取對應庫的函數入口地址

linux 動態鏈接庫的創建和使用
1. 先創建一個動態鏈接庫。源碼如下:
$ cat max.cpp
extern "C"
{
?? ?int max(int a, int b)
?? ?{
?? ??? ?return a>b? a:b;
?? ?}
}
加上extern "C", 是為了導出函數名稱不用C++格式,而用C格式
編譯生成動態庫
g++ -shared -o libmax.so max.cpp

把庫copy 到系統目錄。
sudo cp libmax.so /lib

2. 再創建一個測試用例,源碼如下:
gitserver@gitserver-desktop:~/share/android4.0.3/hjj/pc$ cat test_d.cpp
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>?? ?// 動態加載的函數頭文件
// int max(int a, int b);
typedef int (*maxptr)(int a, int b);
int main(int argc, char *argv[])
{
??????? maxptr max;?? ??? ?// 定義max 型函數指針
??????? void *handle = dlopen("libmax.so",RTLD_LAZY);
??????? if(!handle)
??????? {
??????????????? printf("error open librayry libmax.so");
??????????????? exit(1);
??????? }
??????? max = (maxptr)dlsym(handle,"max");
??????? if(!max)
??????? {
??????????????? char *err=dlerror();
??????????????? printf("%s",err);
??????????????? exit(2);
??????? }
??????? int a=max(3,5);
??????? printf("the bigger is %d\n",a);
??????? dlclose(handle);
??????? return 0;
}

編譯生成可執行文件
g++ -o test test.cpp -ldl

libdl.so 是必需的動態庫

3. 運行可執行文件。
$ ./test
the bigger is 5

注意:
當沒有用extern "C" 包含代碼時, 運行會出現下列錯誤。
/lib/libmax.so: undefined symbol: max
你可以用nm 來查看libmax.so, 看其輸出符號到底是什么,一看,知道應該用C 名稱導出。
其它常見錯誤為:
1.沒有包含dlfcn.h 頭文件, 引起編譯錯誤
test_d.cpp: In function ‘int main(int, char**)’:
test_d.cpp:9:36: error: ‘RTLD_LAZY’ was not declared in this scope
test_d.cpp:9:45: error: ‘dlopen’ was not declared in this scope
test_d.cpp:15:34: error: ‘dlsym’ was not declared in this scope
test_d.cpp:18:21: error: ‘dlerror’ was not declared in this scope
test_d.cpp:24:16: error: ‘dlclose’ was not declared in this scope

2.連接沒有包含libdl.so, 出現連接錯誤
$ g++ -o test_d test_d.cpp ?
/tmp/ccv8xKSN.o: In function `main':
test_d.cpp:(.text+0x19): undefined reference to `dlopen'
test_d.cpp:(.text+0x50): undefined reference to `dlsym'
test_d.cpp:(.text+0x60): undefined reference to `dlerror'
test_d.cpp:(.text+0xbd): undefined reference to `dlclose'
collect2: ld returned 1 exit status

3. 生成動態庫沒有采用-share 選項,出現連接錯誤
$ g++ -o libmax.so max.cpp
/usr/lib/gcc/i686-linux-gnu/4.6.1/../../../i386-linux-gnu/crt1.o: In function `_start':
(.text+0x18): undefined reference to `main'
collect2: ld returned 1 exit status

總結

以上是生活随笔為你收集整理的linux 动态链接库的创建和使用--动态连接的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。