linux 动态链接库的创建和使用--动态连接
生活随笔
收集整理的這篇文章主要介紹了
linux 动态链接库的创建和使用--动态连接
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
linux 動態鏈接庫的創建和使用--動態連接
分類: C 編程 2012-03-25 17:01 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 动态链接库的创建和使用--动态连接的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STM32----摸石头过河系列(四)
- 下一篇: linux 其他常用命令