執行 make 或手動 gcc -o app ... 時,連結器噴出:
undefined reference to `dlclose@GLIBC_2.2.5'
undefined reference to `dlopen@GLIBC_2.2.5'
原因在於程式使用了動態載入庫(libdl),但連結階段未正確引入 -ldl,或引入順序錯誤。
-ldl 並置於最後# 錯誤示範:-ldl 放在前面,連結器尚未看到需要 dl 符號的目標檔
gcc -ldl -o app main.o module.o
# 正確示範:-ldl 放在所有 .o / .a 之後
gcc -o app main.o module.o -ldl
原理:連結器按順序解析符號,只有當 -ldl 出現在需要它的目標檔 之後,未解析的 dlopen、dlclose 等符號才能被正確解決。
| 缺失符號示例 | 對應庫 | 連結參數 |
|---|---|---|
dlerror, dlopen, dlclose | libdl | -ldl |
pthread_create, pthread_mutex_lock | libpthread | -lpthread |
clock_gettime, timer_create | librt | -lrt |
mysql_init, mysql_real_connect | libmysqlclient | -lmysqlclient |
Project → Build options → Linker settings → Other linker options 加入 -ldl -lpthread -lrt;若仍報錯,改在 Link libraries 列表中按依賴順序添加 dl、pthread、rt。target_link_libraries(myapp ${CMAKE_DL_LIBS} pthread rt)。nm -D libmylib.so | grep symbol_name。extern、__attribute__((visibility("default")))。記住「依賴庫後置」原則,undefined reference 就不再是難題。