/usr/bin/ld: zdatabase.o: undefined reference to symbol 'pthread_create@@GLIBC_2.2.5'
/lib/x86_64-linux-gnu/libpthread.so.0: error adding symbols: DSO missing from command line
collect2: error: ld returned 1 exit status
makefile:23: recipe for target 'hello' failed
make: *** [hello] Error 1
鏈接器找不到 pthread 庫。代碼中使用了 pthread_create,編譯階段通過(頭文件 pthread.h 提供聲明),但鏈接階段未指定 -lpthread,導致符號解析失敗。
hello: zdatabase.o
g++ -o hello zdatabase.o # 缺少 -lpthread
# 變量定義
CXX = g++
CXXFLAGS = -Wall -O2 -std=c++11
LDFLAGS = -lpthread # 關鍵:鏈接 pthread 庫
OBJS = zdatabase.o
hello: $(OBJS)
$(CXX) -o $@ $^ $(LDFLAGS)
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c $< -o $@
.PHONY: clean
clean:
rm -f *.o hello
-lpthread 是**鏈接器標誌**,告訴 ld 去查找 libpthread.so/libpthread.a-c 只生成目標文件,不進行符號解析cmake_minimum_required(VERSION 3.10)
project(HelloThreads)
find_package(Threads REQUIRED) # 現代 CMake 方式
add_executable(hello zdatabase.cpp)
target_link_libraries(hello Threads::Threads) # 自動處理 -lpthread 及跨平台
# 檢查 libpthread.so 中是否有 pthread_create
readelf -s /lib/x86_64-linux-gnu/libpthread.so.0 | grep pthread_create
# 輸出應包含:
# 123: 0000000000008a60 922 FUNC WEAK DEFAULT 13 pthread_create@@GLIBC_2.2.5
| 錯誤寫法 | 後果 | 正確寫法 |
|---|---|---|
g++ -lpthread -o hello zdatabase.o | 庫在目標文件前,符號解析失敗 | g++ -o hello zdatabase.o -lpthread |
LDFLAGS = -pthread | 部分平台僅影響編譯器預定義宏 | LDFLAGS = -lpthread (鏈接) 或 CXXFLAGS += -pthread (編譯+鏈接) |
靜態鏈接 -static -lpthread | glibc 不建議靜態鏈接 pthread | 動態鏈接 -lpthread |