CMake链接错误pthread:启用多线程以使用std :: thread:不允许操作

时间:2015-06-09 13:54:28

标签: c++ multithreading cmake pthreads

我有一个像以前一样的错误 C++ Threads, std::system_error - operation not permitted?

我使用完全相同的源代码并使用

进行编译
g++ ../src/main.cpp -pthread -std=c++11

没有任何问题。

因为我想在更大的项目中使用线程,所以我必须使用CMake的线程。在搜索解决方案后,我发现了几个代码:

cmake_minimum_required (VERSION 2.6)
project (Test)
add_definitions("-std=c++11")

find_package (Threads)
add_executable (main src/main.cpp)
target_link_libraries (main ${CMAKE_THREAD_LIBS_INIT})

但对我来说,我不能工作,我总是这样:

terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted
Aborted (core dumped)

我的错误是什么?

CMake输出看起来很有希望:

-- The C compiler identification is GNU 4.8.2
-- The CXX compiler identification is GNU 4.8.2
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Looking for include file pthread.h
-- Looking for include file pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE  
-- Configuring done
-- Generating done

2 个答案:

答案 0 :(得分:15)

修改: 我现在正在使用gcc 5.4,有问题的CMake片段工作正常。

我刚遇到同样的问题。我的最终CMakeList.txt,如下所示(注意 - 它也适用于Windows,即 - 使用Visual Studio):

cmake_minimum_required (VERSION 2.6)
project (Test)
SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11 -pthread")

find_package (Threads)
add_executable (main src/main.cpp)
target_link_libraries (main ${CMAKE_THREAD_LIBS_INIT})

答案 1 :(得分:0)

在我的情况下(Linux桌面),设置标志就足够了:

cmake_minimum_required (VERSION 2.6)
PROJECT (threads_tests)
SET(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11 -pthread")
ADD_EXECUTABLE(threads_1 threads_1.cpp)

但明确地找到库并与其链接也是有效的,并且可能对于嵌入式平台的某些交叉编译情况而言可能是必要的。