简体   繁体   中英

CMake undefined reference to `pthread_create` in Github Action Ubuntu image

When I was using Github Action CI, I found that no matter what method I used to link, there was no way to link pthread_create

But this error only appears in the Ubuntu environment, Windows, macOS are no problem

I tried:

  1. Not Working

    set(CMAKE_THREAD_PREFER_PTHREAD TRUE) set(THREADS_PREFER_PTHREAD_FLAG TRUE) find_package(Threads REQUIRED) add_executable(xxx xxx.c) target_link_libraries(xxx PRIVATE Threads::Threads)
  2. Not Working

    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -pthread")

You can view the compiled log here:

https://github.com/YuzukiTsuru/lessampler/runs/6640320037?check_suite_focus=true

If you read the build log carefully

/usr/bin/ld: CMakeFiles/GenerateAudioModelTest.dir/__/src/GenerateAudioModel.cpp.o: in function `GenerateAudioModel::GenerateModelFromFile()':
GenerateAudioModel.cpp:(.text+0x27aa): undefined reference to `pthread_create'

You notice the error has happened while linking the target GenerateAudioModelTest that is located in the directory test and CMakeLists.txt there does not have the compiler flags you shown. Just add -pthread in test/CMakeLists.txt .


This is a bad idea.

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -pthread")

Use

target_compile_options(GenerateAudioModelTest PRIVATE -pthread)

See What is the modern method for setting general compile flags in CMake?

  1. Not Working

You did not link with Thread::Thread nor any library that the target links to.

https://github.com/YuzukiTsuru/lessampler/blob/a6bb7e7d7ac30b6b4043d4f717a2d4deb7fb7638/test/CMakeLists.txt#L22

  1. Not Working

Flags have to be set before add_executable . Which means before all the add_subdirectories . And flags have directory scope. Use targe_compile_options .

https://github.com/YuzukiTsuru/lessampler/blob/master/src/CMakeLists.txt

  1. Consider just making it one library, why so many, and so many CMakeLists.txt in every directory. If the tools are not so separate and you are never going to use them separately, just make it one library with one CMakeLists.txt that links with all the libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM