Tag Archives: undefined reference to ‘pthread_create’

Undefined reference to ‘pthread’ appears in Linux Ubuntu running thread program_ Create ‘and undefined reference to’ pthread ‘_ ‘join’ error.

Undefined reference to ‘pthread’ appears in Linux Ubuntu running thread program_ Create ‘and undefined reference to’ pthread ‘_ ‘join’ error

Write good thread code, compile

gcc xiancheng.c -o xiancheng

The following prompt appears

1 linux@ubuntu64-vm:~/workdir$ gcc xiancheng.c -o xiancheng
2 /tmp/ccOCxLrd.o: In function `main':
3 xiancheng.c:(.text+0x11e): undefined reference to `pthread_create'
4 xiancheng.c:(.text+0x131): undefined reference to `pthread_join'
5 collect2: ld return 1
6 linux@ubuntu64-vm:~/workdir$

The reason for the problem: the pthread header file is included in the header file reference of the program, and it is not the default library under Linux, that is, when linking, the entry address of the function in the phread library cannot be found, so the link will fail

#include <pthread.h>

Solution: when compiling GCC, add the – lpthread parameter

Compile using the following code

gcc xiancheng.c -o xiancheng -lpthread

You can pass

Cmake solves the problem of phread Library in C + + 11: undefined reference to ` pthread_ create’

Method 1

PROJECT(HELLO)
set(CMAKE_CXX_FLAGS "${CAMKE_CXX_FLAGS} -std=c++11")
AUX_SOURCE_DIRECTORY(. SRC_LIST)
ADD_EXECUTABLE(hello ${SRC_LIST})

From the cmakelists.txt file of cmake, we can see that cmake has – STD = C + + 11, just like G + + uses C + + 11, so we can add – pthread to solve it

PROJECT(HELLO)
set(CMAKE_CXX_FLAGS "${CAMKE_CXX_FLAGS} -std=c++11 -pthread")
AUX_SOURCE_DIRECTORY(. SRC_LIST)
ADD_EXECUTABLE(hello ${SRC_LIST})

Method 2

Using package threads and link ${cmake_ THREAD_ LIBS_ INIT}

PROJECT(HELLO)
set(CMAKE_CXX_FLAGS "${CAMKE_CXX_FLAGS} -std=c++11")
FIND_PACKAGE(Threads)
AUX_SOURCE_DIRECTORY(. SRC_LIST)
ADD_EXECUTABLE(hello ${SRC_LIST})
TARGET_LINK_LIBRARIES(hello ${CMAKE_THREAD_LIBS_INIT})