【问题标题】:What are the correct link options to use std::thread in GCC under linux?在 linux 下的 GCC 中使用 std::thread 的正确链接选项是什么?
【发布时间】:2021-07-09 01:56:47
【问题描述】:

您好,我正在尝试将 std::thread 与 G++ 一起使用。这是我的测试代码

#include <thread>
#include <iostream>

int main(int, char **){
    std::thread tt([](){ std::cout<<"Thread!"<<std::endl; });
    tt.join();
}

它可以编译,但是当我尝试运行它时,结果是:

terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted 
Aborted

我的编译器版本:

$ g++ --version
g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

我的测试代码有什么问题?

更新:我使用以下命令行来编译和运行我的代码。

$ g++ -std=c++0x test.cpp
$ ./a.out

我试过了

$ g++ -std=c++0x -lpthread test.cpp
$ ./a.out

还是一样。

【问题讨论】:

  • @Earth Engine:这个 SO 答案解释了为什么没有 pthread 库就没有链接错误:stackoverflow.com/a/6266345/12711 简短回答:glibc 对许多 pthread 函数都有无用的存根。
  • @EarthEngine 你能把解决方案放在答案中吗?特别是-lpthread 必须跟随源文件。

标签: c++ multithreading g++ c++11


【解决方案1】:

我认为在 Linux 上 pthread 是用来实现 std::thread 所以你需要指定 -pthread 编译器选项。

由于这是一个链接选项,这个编译器选项需要AFTER源文件:

$ g++ -std=c++0x test.cpp -pthread

【讨论】:

  • 我正在尝试使用 gcc 4.7.1 编译一个非常简单的程序,但我遇到了同样的“不允许操作”错误。问题是我已经在使用 -pthread 标志。你还知道其他标志吗?
  • 我解决了从链接器选​​项中删除“-static”标志的问题,不知道为什么会这样
  • 我想知道为什么编译器在没有 -lpthread 选项的情况下编译时不会出错。有人吗??
  • 在 Ubuntu 14.04 g++ --version (g++ (Ubuntu/Linaro 4.8.1-10ubuntu9) 4.8.1) 下我必须添加 -W1, --no-as-needed g++ --std =c++11 -Wl, --no-as-needed -pthread main.cc
  • -Wl,--whole-archive -lpthread -Wl,--no-whole-archive 解决了问题,而不是 -pthread。这是链接问题link 根据man gcc -pthread 只是g++ 选项,它添加了为预处理器和链接器设置标志的多线程支持
【解决方案2】:

除了使用-std=c++0x-pthread 之外,您还必须使用-static

【讨论】:

    【解决方案3】:

    -std=c++11 -static -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive-static 一起使用!!!

    请看这里:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52590#c4

    【讨论】:

    • 使用--whole-archive 会变得非常庞大。我发现 another answer 用于静态链接在 OpenWRT 上对我有用
    【解决方案4】:

    这是一个用于编译使用线程的 C++11 程序的简单 CMake 文件:

    CMakeLists.txt:

    cmake_minimum_required(VERSION 2.8)
    list(APPEND CMAKE_CXX_FLAGS "-pthread -std=c++11 ${CMAKE_CXX_FLAGS}")
    add_executable(main main.cpp)
    

    一种构建方式是:

    mkdir -p build
    cd build
    cmake .. && make
    

    【讨论】:

    • 您的解决方案对我来说对 hmjd 的回答没有任何改进,并添加了一些不必要的东西(分析、测试覆盖)
    【解决方案5】:

    尝试在单个命令中以这种方式编译:

    g++ your_prog.cpp -o your_output_binary -lpthread -std=gnu++11
    

    您也可以尝试使用 C++11 代替 gnu++11。希望这行得通。

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 2012-11-06
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 2013-07-15
      相关资源
      最近更新 更多