C++ 如何在 Qt Creator 上使用 pthread

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11710524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:26:49  来源:igfitidea点击:

How to use pthread on Qt Creator

c++qtc++11qt-creator

提问by hizz

I want to execute a following code.

我想执行以下代码。

#include <iostream>
#include <thread>

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

int main()
{
    std::thread t(output);
    t.join();

    return 0;
}

I can't execute it.

我无法执行它。

Qt Creator outputs terminate called after throwing an instance of 'std::system_error' what(): Operation not permitted

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

However I can execute on the terminal using the option of -pthread. Could you tell me how to use the option of -pthread in Qt Creator?

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

My developing environment is Ubuntu(12.04), g++4.6.3, Qt Creator(2.4.1).

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

Thank you.

谢谢你。

回答by Stephan Dollberg

You also need to link against -pthread. If you use g++ main.cpp -std=c++0x -pthreadyou are doing all that in one step, so it works correctly. To make Qt do the correct things, add the following to your project file:

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

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

回答by Andrew Tomazos

This works for me:

这对我有用:

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

# Input
SOURCES += test.cpp

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

Your example compiles and executes correctly with the above .pro file on my system.

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

Try save your example as test.cpp, and the above as project.pro in same directory. Then type:

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

$ qmake
$ make
$ ./project
Hello World

回答by Stephen Chu