用g ++编译多线程代码

时间:2013-10-19 07:29:55

标签: c++ linux ubuntu gcc g++

我有最简单的代码:

#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)

现在我陷入了困境。在互联网上的每个相关主题中,建议在我拥有它的同时添加-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:伙计们,这不是What is the correct link options to use std::thread in GCC under linux?

的副本

PPPPPS:

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

4 个答案:

答案 0 :(得分:73)

答案是由SO C++ chat的一位成员提供的。

看起来这种行为是由gcc中的bug引起的。

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

-Wl,--no-as-needed

答案 1 :(得分:28)

添加-lpthread为我解决了同样的问题:

 g++ -std=c++11 foo.cpp -lpthread -o foo

答案 2 :(得分:9)

答案已经完成了 对于qtcreator:

LIBS += -pthread
QMAKE_CXXFLAGS += -pthread
QMAKE_CXXFLAGS += -std=c++11

for console g ++:here

g++ -c main.cpp -pthread -std=c++11         // generate target object file
g++ main.o -o main.out -pthread -std=c++11  // link to target binary

答案 3 :(得分:9)

我有更高级的版本(4.8.4而不是4.8.1),我测试了上面的所有三个答案。事实上:

-pthread单独工作:

  

g ++ -std = c ++ 11 -o main -pthread main.cpp

-Wl,--no-as-needed 无效

-lpthread 无效

-Wl,--no-as-needed-lpthread 一起 工作:

  

g ++ -std = c ++ 11 -o main -Wl, - no-as-needed main.cpp -lpthread

我的版本是&#34; g ++(Ubuntu 4.8.4-2ubuntu1~14.04.1)4.8.4&#34;。