如何在 Qt Creator 上使用 pthread

Posted

技术标签:

【中文标题】如何在 Qt Creator 上使用 pthread【英文标题】:How to use pthread on Qt Creator 【发布时间】:2012-07-29 15:40:06 【问题描述】:

我想执行下面的代码。

#include <iostream>
#include <thread>

void output() 
    std::cout << "Hello World" << std::endl;


int main()

    std::thread t(output);
    t.join();

    return 0;

我无法执行它。

Qt Creator 输出 在抛出 'std::system_error' 的实例后调用终止 what(): 不允许操作

但是我可以使用 -pthread 选项在终端上执行。 您能告诉我如何在 Qt Creator 中使用 -pthread 选项吗?

我的开发环境是Ubuntu(12.04)、g++4.6.3、Qt Creator(2.4.1)。

谢谢。

【问题讨论】:

【参考方案1】:

您还需要链接到-pthread。如果您使用g++ main.cpp -std=c++0x -pthread,您将一步完成所有操作,因此它可以正常工作。要让 Qt 做正确的事情,请将以下内容添加到您的项目文件中:

QMAKE_CXXFLAGS += -std=c++0x -pthread 
LIBS += -pthread

【讨论】:

谢谢,但它不起作用。在抛出 'std::system_error' what(): 的实例后调用 Qt Creator 输出终止。但是,在调试中,它正在工作。这是什么意思? @hizz 你在更改 .pro 文件后重建了你的项目吗? 哦,重建项目后它正在工作。从现在开始我会小心的。 谢谢,它对我有用。唯一需要的是最后一条语句。 @bamboon 我已经包含了 pthread,为什么我还需要设置 LIBS,这真的让我很困惑。【参考方案2】:

这对我有用:

TEMPLATE = app
TARGET = 
DEPENDPATH += .
INCLUDEPATH += .

# Input
SOURCES += test.cpp

QMAKE_CXXFLAGS += -std=gnu++0x -pthread
QMAKE_CFLAGS += -std=gnu++0x -pthread

您的示例在我的系统上使用上述 .pro 文件正确编译和执行。

尝试将您的示例保存为 test.cpp,并将上述示例保存为 project.pro 在同一目录中。然后输入:

$ qmake
$ make
$ ./project
Hello World

【讨论】:

感谢您的回复。但是,它不起作用。在抛出“std::system_error”what() 实例后调用 Qt Creator 输出终止:不允许操作。 对不起,我打错了。再试一次。 谢谢。不幸的是,它也不起作用。我通过在终端上键入“g++ test.cpp -std=c++0x -pthread”或“g++ test.cpp -std=gnu0x -pthread”来确认执行。有什么问题?谢谢。 使用上面的新 .pro 文件重试。并将 make 的输出粘贴到您的答案中。 谢谢。我已经尝试过了,但它不起作用。在抛出 'std::system_error' what(): 的实例后调用 Qt Creator 输出终止。但是,在调试模式下,它正在工作。这是什么意思?【参考方案3】:

在此处添加您的命令行参数: http://doc.qt.nokia.com/qtcreator-2.4/creator-run-settings.html

【讨论】:

谢谢。我可以在这里添加构建选项吗?

以上是关于如何在 Qt Creator 上使用 pthread的主要内容,如果未能解决你的问题,请参考以下文章

如何在Ubuntu上的某些样式表中运行qt creator?

使用 QT Creator,如何制作不需要在目标平台上安装 .dll 的 Windows 可执行文件? [复制]

如何配置 Qt Creator 以在 centos 6.7 上使用 RH 的 devtoolset-2?

如何向 Qt Creator 添加新工具包

在 Windows 上使用 Qt Creator 设置 ccache

如何在 QT Creator 中使用 mingw 在多核上编译