動態庫*.so製作-linux
linux動態庫.so基礎知識製作 在linux下製作動態庫*.so。 1、linux下動態庫的製作//so_test.h#include "stdio.h"void test_a();void test_b();void test_c(); //test_a.c#include "so_test.h"void test_a(){printf("this is in test_a...\n");} //test_b.c#include "so_test.h"void test_b(){printf("this is in test_b...\n");} //test_c.c#include "so_test.h"void test_c(){printf("this is in test_c...\n");} 產生動態庫:libtest.so# gcc test_a.c test_b.c test_c.c -fPIC -shared -o libtest.so 2、動態庫與標頭檔位置# cp libtest.so /lib/# cp so_test.h /usr/include/ 3、動態庫的連結測試程式 //test.c#include <so_test.h>int main(){test_a();test_b();test_c();return 0;} 將test.c與動態庫libtest.so連結產生執行檔案test:# gcc test.c -L. -ltest -o test 測試是否動態串連,如果列出libtest.so,那麼應該是串連正常了# ldd test 4、編譯參數解析 -shared:該選項指定產生動態串連庫(讓連接器產生T類型的匯出符號表,有時候也產生弱串連W類型的匯出符號);不用該標誌外部程式無法串連,相當於一個可執行檔; -fPIC:表示編譯為位置獨立的代碼;不用此選項的話編譯後的代碼是位置相關的所以動態載入時是通過代碼拷貝的方式來滿足不同進程的需要,而不能達到真正程式碼片段共用的目的; -L.:表示要串連的庫在目前的目錄中 -ltest:編譯器尋找動態串連庫時---隱含的命名規則[注釋:libtest.so == -ltest / libhello.so == -lhello ] LD_LIBRARY_PATH:這個環境變數指示動態連接器可以裝載動態庫的路徑。修改/etc/ld.so.conf檔案,然後調用 /sbin/ldconfig來達到同樣的目的,不過如果沒有root許可權,那麼只能採用輸出LD_LIBRARY_PATH的方法了。