在鏈接 OpenSSL 靜態庫 libcrypto.a 和 libssl.a 時,編譯器報告大量 undefined reference 錯誤,涉及 pthread_setspecific、pthread_getspecific、pthread_key_create、dlopen、dlsym、dlclose、dlerror、dladdr 等符號。
OpenSSL 靜態庫依賴系統的 pthread(線程庫)和 dl(動態加載庫),但靜態鏈接時不會自動引入這些依賴,必須在鏈接命令中顯式指定。
gcc obj/Debug/main.o -L/usr/local/openssl/lib -lssl -lcrypto -ldl -lpthread -o main
-L/usr/local/openssl/lib 指向編譯好的 OpenSSL 庫目錄。-lssl -lcrypto 必須在 -ldl -lpthread 之前。鏈接器按順序解析符號,後面的庫用於滿足前面庫的未解析引用。ssl、crypto、dl、pthread。| 參數 | 含義 |
|---|---|
-L | 指定鏈接庫搜索路徑 |
-l (小寫 L) | 鏈接指定庫,如 -lssl 尋找 libssl.a 或 libssl.so |
-I (大寫 i) | 指定頭文件搜索路徑 |
-lpthread 放在 -lcrypto 之前,導致符號無法解析。LD_LIBRARY_PATH 或 rpath,運行時報錯。