【问题标题】:C++ Threads, std::system_error - operation not permitted? [duplicate]C++ 线程,std::system_error - 不允许操作? [复制]
【发布时间】:2013-06-24 11:09:32
【问题描述】:

所以我写了一个程序来测试 64 位 kubuntu linux 上的线程,版本 13.04。实际上是我从正在编写测试程序的其他人那里窃取了代码。

#include <cstdlib>
#include <iostream>
#include <thread>

void task1(const std::string msg)
{
    std::cout << "task1 says: " << msg << std::endl;
}

int main(int argc, char **argv)
{
    std::thread t1(task1, "Hello");
    t1.join();

    return EXIT_SUCCESS;
}

我编译使用:

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

然后跑:

./main.out

顺便说一句,当我输入“ls -l”时,main.out 与所有可执行文件一样以绿色文本显示,但名称末尾也有一个星号。这是为什么呢?

回到手头的问题:我跑main.out的时候,出现了一个错误,里面说:

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

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: c++ multithreading c++11 std-system-error


    【解决方案1】:

    您没有正确链接 pthread,请尝试以下命令(注意:顺序很重要)

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

    用两个命令来做

    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
    

    【讨论】:

    • 你可以用两个命令来完成。但是在编译和链接时都必须指定-pthread
    • 好的,谢谢大家,现在可以使用了!
    • @billz 你介意详细说明为什么 -pthread 的顺序很重要吗?
    • 链接前需要先编译。将-pthread int放在g++命令的末尾将允许g++在编译到.o文件后正确链接
    • -pthread 的 GCC 手册条目明确指出“此选项为预处理器和链接器设置标志。”您应该在编译和链接时使用它。
    猜你喜欢
    • 2014-02-03
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多