小编典典

用G ++编译多线程代码

linux

我有史以来最简单的代码:

#include <iostream>
#include <thread>

void worker()
{
    std::cout << "another thread";
}

int main()
{
    std::thread t(worker);
    std::cout << "main thread" << std::endl;
    t.join();
    return 0;
}

尽管我仍然无法编译g++运行它。

更多细节:

$ g++ --version
g++ (Ubuntu/Linaro 4.8.1-10ubuntu8) 4.8.1
Copyright (C) 2013 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++ main.cpp -o main.out -pthread -std=c++11

运行:

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

现在我陷入困境。在Internet上的每个相关线程中,建议在-pthread已经拥有的情况下添加它。

我究竟做错了什么?

PS:这是全新的ubuntu 13.10安装。只有g++包安装和次要之类的东西chromium

PPS:

$ ldd ./a.out 
linux-vdso.so.1 => (0x00007fff29fc1000) 
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fb85397d000) 
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fb853767000) 
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fb85339e000) 
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fb85309a000) 
/lib64/ld-linux-x86-64.so.2 (0x00007fb853c96000)

PPPS:使用clang++(v3.2)可以编译并正常运行

PPPPS:伙计们,这不是Linux下在GCC中使用std ::thread的正确链接选项是什么的重复项?

PPPPPS:

$ dpkg --get-selections | grep 'libc.*dev'
libc-dev-bin                    install
libc6-dev:amd64                 install
libclang-common-dev             install
linux-libc-dev:amd64                install

阅读 303

收藏
2020-06-02

共1个答案

小编典典

答案是由SO C++聊天的一位好心人提供的。

看来此行为是由gcc中的错误引起的。

该错误讨论的最后评论中提供的解决方法 确实 可以解决该问题:

-Wl,--no-as-needed
2020-06-02