使用 g++ 编译多线程代码

Compiling multithread code with g++

本文关键字:代码 多线程 编译 g++ 使用      更新时间:2023-10-16

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

#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:伙计们,它不是在 Linux 下在 GCC 中使用 std::thread 的正确链接选项是什么的副本?

购买力平价:

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

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

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

该错误讨论的最后一条评论中提供的解决方法确实有效并解决了该问题:

-Wl,--no-as-needed

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

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

我有稍微高级的版本(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-need main.cpp -lpthread

我的版本是"g++ (Ubuntu 4.8.4-2ubuntu1~14.04.1) 4.8.4"。

答案已经给出对于 qtcreator:

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

对于控制台 G++:此处

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