ld "undefined reference to pthread_create" (missing -pthread) in CI
pthread_create and friends live in the threads runtime. Without -pthread on both compile and link, the symbols are undefined at link time.
What this error means
Code that uses std::thread or raw pthreads fails to link with "undefined reference to pthread_create", though it compiles cleanly.
ld
/usr/bin/ld: main.o: in function 'main':
main.cpp:(.text+0x2c): undefined reference to 'pthread_create'
collect2: error: ld returned 1 exit statusCommon causes
How to fix it
Add -pthread
- Pass -pthread to both compilation and linking.
- In CMake, link Threads::Threads via find_package(Threads REQUIRED).
ld
g++ -pthread main.cpp -o app
# CMake
find_package(Threads REQUIRED)
target_link_libraries(app PRIVATE Threads::Threads)How to prevent it
- Use -pthread (or CMake Threads::Threads) for any code that touches std::thread or pthreads so the runtime is always linked.