# C/C++: undefined reference to `pthread_create' — missing -pthread (also `dlopen`, `clock_gettime`)

**Code:** `undefined reference to pthread_create` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang, CMake

Your program uses threads (or another system library) but the linker was not told to link it.

## Meaning

On many Linux systems the thread functions live in `libpthread`, and `dlopen` in `libdl`, `clock_gettime` in `librt`. With glibc 2.34+ these moved into libc, but older systems and static builds still need the flag. Use `-pthread` (compile and link) or CMake's `Threads::Threads`.

## Common causes

- `std::thread` or pthread functions used without `-pthread`
- `dlopen`/`dlsym` without `-ldl` on older glibc
- `clock_gettime`/`shm_open` without `-lrt` on older glibc
- Library listed before the object files that need it

## Quick fix

1. Add `-pthread` to compile and link flags
2. Link `Threads::Threads` in CMake
3. Put libraries after the sources: `g++ main.cpp -pthread -ldl`

## Detailed fix by platform

### GCC / Clang

1. `g++ -std=c++17 main.cpp -o app -pthread`
2. Order matters for static libraries: sources first, then `-l` flags

### CMake

1. `find_package(Threads REQUIRED)` and `target_link_libraries(app PRIVATE Threads::Threads)`

## Code examples

### Linking threads correctly

```cmake
find_package(Threads REQUIRED)
add_executable(app main.cpp)
target_link_libraries(app PRIVATE Threads::Threads ${CMAKE_DL_LIBS})
```

## How to diagnose

1. **Symbol** — Which function is missing?
2. **Flag** — Is -pthread used at link time?
3. **Order** — Are libraries after the objects?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/undefined-reference-pthread-create)
