庫是代碼復用的核心機制。本文從「為什麼需要庫」切入,系統講解靜態庫 (.a)與動態庫 (.so)的區別、創建流程、鏈接機制、運行時搜尋路徑、調試工具,並提供完整可編譯實戰範例。
| 維度 | 靜態庫 (.a) | 動態庫 (.so) |
|---|---|---|
| 鏈接階段 | 編譯時 (靜態鏈接) | 運行時 (動態鏈接) |
| 可執行文件體積 | 較大 (包含庫代碼副本) | 較小 (僅存符號引用) |
| 磁碟空間 (多程序共用) | 浪費 (每程序一份副本) | 節省 (內存中僅一份副本) |
| 升級修復 Bug | 需重新編譯所有依賴程序 | 替換 .so 文件即可 (兼容前提下) |
| 部署獨立性 | 強 (無外部依賴) | 弱 (目標機需有對應 .so) |
| 運行性能 | 略快 (無動態鏈接開銷) | 略慢 (啟動時符號解析、PLT/GOT) |
| 調試難度 | 符號內嵌,易調試 | 需符號表、源碼路徑映射 |
// hello.c
#include
void hello(void) {
printf("Hello World\n");
}
gcc -shared -fPIC hello.c -o libhello.so
# -fPIC: 產生位置無關代碼 (動態庫必須)
# -shared: 生成共享對象
驗證:
$ file libhello.so
libhello.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), not stripped
// test.c
void hello(void);
int main() {
hello();
return 0;
}
# 編譯鏈接 (指定庫搜尋路徑 .)
gcc test.c -L. -lhello -o test_dynamic
# 查看動態依賴
$ ldd test_dynamic
linux-vdso.so.1 => (0x00007ffc12345000)
libhello.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f1234567000)
/lib64/ld-linux-x86-64.so.2 (0x00007f1234568000)
關鍵問題:動態鏈接器 (ld-linux.so) 找不到 libhello.so。
| 方法 | 命令/配置 | 優先級/範圍 |
|---|---|---|
| 環境變量 LD_LIBRARY_PATH | export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH | 進程級,最高優先級,開發測試用 |
| /etc/ld.so.conf + ldconfig | echo "/path/to/lib" >> /etc/ld.so.conf; ldconfig | 系統級,永久生效,需 root |
| 安裝到標準目錄 | cp libhello.so /usr/local/lib/; ldconfig | 系統級,標準路徑 (/lib, /usr/lib, /usr/local/lib) |
設置後 ldd test_dynamic 顯示 libhello.so => ./libhello.so,運行 ./test_dynamic 輸出 Hello World。
# 1. 生成目標文件
gcc -c hello.c -o hello.o
# 2. 歸檔為靜態庫
ar rcs libhello.a hello.o
# r: 插入/替換 c: 創建 s: 建立索引 (等同 ranlib)
# 3. 靜態鏈接
gcc test.c -L. -lhello -static -o test_static
# 4. 驗證
$ file test_static
test_static: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped
$ ldd test_static
not a dynamic executable
-L 指定的目錄 (按順序)LIBRARY_PATH/usr/local/lib, /lib, /usr/lib (由 specs 文件決定)-static 或 -Wl,-Bstatic| 工具 | 用途 | 典型命令 |
|---|---|---|
file | 識別文件類型 (shared object / executable / archive) | file libhello.so |
ldd | 列出動態依賴及解析路徑 | ldd test_dynamic |
nm | 列出符號表 | nm -D libhello.so (動態符號) |
objdump | 反彙編、段信息 | objdump -T libhello.so |
readelf | ELF 結構深度分析 | readelf -d libhello.so (動態段) |
ldconfig -p | 查看緩存的庫搜尋路徑 | ldconfig -p | grep hello |
| 錯誤 | 原因 | 解決 |
|---|---|---|
| undefined reference to `func' | 缺少庫或庫順序錯誤 | 調整 -l 順序:依賴庫放後面;補充 -L 路徑 |
| cannot find -lname | 庫文件不在搜尋路徑 | 加 -L/path 或設置 LIBRARY_PATH |
| error while loading shared libraries | 運行時找不到 .so | LD_LIBRARY_PATH / ldconfig / 標準目錄 |
| multiple definition of `func' | 重複鏈接同一符號 | 檢查靜態庫重複、頭文件內聯函數、模板實例化 |