頭文件 test.h:
#include <stdio.h>
void first();
void second();
void third();
實現文件:
// first.c
#include "test.h"
void first() { printf("this is first.\n"); }
// second.c
#include "test.h"
void second() { printf("this is second.\n"); }
// third.c
#include "test.h"
void third() { printf("this is third.\n"); }
gcc first.c second.c third.c -fPIC -shared -o libtest.so
-fPIC:生成位置無關代碼,支援共享庫加載到任意地址-shared:指定輸出為共享庫而非可執行文件lib.so // test.c
#include "test.h"
void main() {
first();
second();
third();
}
gcc test.c -L. -ltest -o test
-L.:指定庫搜索路徑為當前目錄-ltest:按慣例查找 libtest.so./test
# 輸出:
this is first.
this is second.
this is third.
錯誤: error while loading shared libraries: libtest.so: cannot open shared object file
方案一:配置 ld.so.conf
echo "/your/lib/path" | sudo tee /etc/ld.so.conf.d/test.conf
sudo ldconfig
方案二:創建軟鏈接
ln -s /your/lib/path/libtest.so /usr/lib/
方案三:設置環境變量 (臨時)
export LD_LIBRARY_PATH=/your/lib/path:$LD_LIBRARY_PATH
libtest.so.1.0.0 + soname + 符號鏈接鏈-fvisibility=hidden + __attribute__((visibility("default"))) 導出控制extern "C" 防止名字修飾ldd test 查看依賴、nm -D libtest.so 列導出符號掌握動態庫構建是 Linux 系統編程、模組化架構、插件機制的基石技能。