靜態庫(.a)將多個目標檔(.o)打包,連結時將符號解析並複製進可執行檔,無執行期依賴,適合嵌入式、發布單一二進制、效能關鍵路徑。本文示範從源碼編譯、ar 打包、連結測試、安裝至系統路徑的標準流程。
// hello_first.c
void hello_first(void) { printf("hello first\n"); }
// hello_second.c
void hello_second(void) { printf("hello second\n"); }
$ gcc -c hello_first.c -o hello_first.o
$ gcc -c hello_second.c -o hello_second.o
$ ar rcs libhello.a hello_first.o hello_second.o
# r: 插入/替換, c: 不提示建立, s: 建立索引 (等同 ranlib)
$ ar t libhello.a
hello_first.o
hello_second.o
$ nm -s libhello.a # 查看符號表
// hello_main.c
#include
void hello_first(void);
void hello_second(void);
int main() {
hello_first();
hello_second();
return 0;
}
$ gcc hello_main.c libhello.a -o hello_main
$ ./hello_main
hello first
hello second
$ sudo cp libhello.a /usr/local/lib/
$ gcc hello_main.c -L/usr/local/lib -lhello -o hello_main2
$ ./hello_main2
hello first
hello second

1. -L 指定目錄 (左至右)
2. 環境變數 LIBRARY_PATH
3. /usr/lib/gcc/.../ (GCC 內建)
4. /usr/lib, /lib (系統預設)
5. /etc/ld.so.conf 內路徑 (執行期 ld.so 也用)
同名動態庫(.so)優先於靜態庫(.a),強制靜態連結:-Wl,-Bstatic -lhello -Wl,-Bdynamic 或 gcc -static hello_main.c -lhello(全靜態,需 glibc-static)。
static。libhello.a 對應單一版本,重大變更改名 libhello_v2.a。hello_。gcc -ffunction-sections -fdata-sections -Wl,--gc-sections 移除未引用段。gcc main.o -lA -lB A 依賴 B)。inline/static 或重複包含實作。掌握 ar/gcc 靜態庫工具鏈,能構建零依賴、高效能、易部署的 C/C++ 元件。