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 下靜態庫、共享庫、動態庫的製作與使用完整指南

編輯:Linux 教學

三類庫的核心差異

類型後綴鏈接時機運行依賴體積特徵
靜態庫.a編譯鏈接期無可執行文件大
共享庫.so.x.y程序啟動時載入需庫文件存在可執行文件小
動態庫.so首次調用符號時載入需庫文件存在可釋放內存

命名與搜索規則

  • 文件名統一為 lib.a/.so
  • 鏈接參數 -l 自動匹配 lib
  • 搜索路徑:-L 指定目錄 → LD_LIBRARY_PATH → /etc/ld.so.conf → /usr/lib、/lib
  • 更新共享庫後需執行 ldconfig

實戰:從靜態庫到共享庫的完整流程

1. 靜態庫 libhello.a

# hello.h
void print_hello(void);

# hello.c
#include <stdio.h>
void print_hello(void) { puts("Hello from static lib"); }

# 編譯
gcc -c hello.c -o hello.o
ar rcs libhello.a hello.o

# 使用
gcc -o use_static usehello.c -L. -lhello  # 或直接 gcc usehello.c libhello.a

2. 共享庫 libhello.so.0.0

# 編譯位置無關代碼
gcc -fPIC -c hello.c -o hello.o
gcc -shared -Wl,-soname,libhello.so.0 -o libhello.so.0.0 hello.o

# 建立軟鏈接(供鏈接器與運行期查找)
ln -sf libhello.so.0.0 libhello.so.0
ln -sf libhello.so.0   libhello.so

# 使用
gcc -o use_dynamic usehello.c -L. -lhello
LD_LIBRARY_PATH=. ./use_dynamic  # 臨時指定運行路徑

3. 同名靜/共享庫共存時的選擇

默認優先鏈接共享庫。強制用靜態庫:gcc -o test test.c -Wl,-Bstatic -lhello -Wl,-Bdynamic 或直接指定 libhello.a 路徑。

關鍵工具

  • ldd:查看可執行文件依賴的共享庫
  • nm / objdump:查看符號表
  • ar:靜態庫打包/解包
Copyright © Windows教程網 All Rights Reserved