首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ Makefile 鏈接錯誤:undefined reference to pthread_create 解決方案

     編輯:程式設計綜合問答

錯誤現象

/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,導致符號解析失敗。

核心修正:Makefile 添加鏈接標誌

錯誤 Makefile 片段

hello: zdatabase.o
    g++ -o hello zdatabase.o  # 缺少 -lpthread

正確 Makefile 片段

# 變量定義
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 只生成目標文件,不進行符號解析
  • GCC 鏈接器**順序敏感**:庫必須放在**依賴它的目標文件之後**

進階:CMakeLists.txt 寫法

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

常見坑位

總結

undefined reference to pthread_create 本質是 **Makefile 鏈接命令缺少 -lpthread 且順序正確**。現代專案建議使用 CMake find_package(Threads) 自動處理,手寫 Makefile 時記住:**庫標誌放在目標文件後,-lpthread 不可少**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
錯誤寫法後果正確寫法
g++ -lpthread -o hello zdatabase.o庫在目標文件前,符號解析失敗g++ -o hello zdatabase.o -lpthread
LDFLAGS = -pthread部分平台僅影響編譯器預定義宏LDFLAGS = -lpthread (鏈接) 或 CXXFLAGS += -pthread (編譯+鏈接)
靜態鏈接 -static -lpthreadglibc 不建議靜態鏈接 pthread動態鏈接 -lpthread