Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 靜態庫、動態庫與 libtool 存檔(.a/.so/.la) 區別詳解

編輯:Linux 教學

文件類型對照表

擴展名類型說明對應 Windows
.o目標文件編譯產出,未鏈接.obj
.a靜態庫多個 .o 打包,編譯時鏈接進可執行文件.lib
.so共享庫/動態庫運行時動態加載,多進程共享內存.dll
.lalibtool 存檔文本配置文件,記錄庫依賴與安裝路徑無直接對應
.ko內核模組Linux 內核動態加載模塊.sys

建立範例

1. 編譯目標文件 .o

gcc -c test.c          # 生成 test.o

2. 建立靜態庫 .a

ar -r libtest.a test1.o test2.o

3. 建立動態庫 .so

gcc -Wall -fPIC -shared test1.c test2.c -o libtest.so
  • -fPIC:位置無關代碼,動態庫必須
  • -shared:生成共享庫

4. 鏈接靜態庫生成動態庫

gcc -Wall -fPIC -shared -L. test3.c -ltest -o libtest.so

5. 使用 libtool 生成 .la

libtool --mode=link gcc -o libmylib.la -rpath /usr/lib test1.lo test2.lo

.la 文件內容為文本,可 cat libmylib.la 查看依賴庫路徑、版本資訊。

鏈接優先級與最佳實踐

  • 編譯器預設優先尋找動態庫 (.so),再尋找靜態庫 (.a)
  • 強制靜態鏈接:gcc -static -o app main.c -ltest
  • 運行時動態庫搜尋路徑:LD_LIBRARY_PATH、/etc/ld.so.conf、/lib、/usr/lib
  • 執行 ldconfig 更新緩存

查看庫依賴

ldd /path/to/executable        # 可執行文件依賴
objdump -p libtest.so | grep NEEDED  # 動態庫聲明依賴
Copyright © Windows教程網 All Rights Reserved