gpt4 book ai didi

c++ - 如何使用 MinGW 编译 C++ std::thread 代码?

转载 作者:行者123 更新时间:2023-11-30 05:12:42 33 4
gpt4 key购买 nike

我想用 MinGW 编译我的 c++11 项目(最近移至 c++11)。而且我有关于 c++11 代码的编译错误,如“std::thread not found”。

我将最后一个 MinGW 与 gcc 5.3.0(2015 年 12 月)一起使用。最后,我只想编译这个例子来编译我的大项目:

#include <iostream>
#include <thread>
#include <chrono>

void foo()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar()
{
// simulate expensive operation
std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main()
{
std::cout << "starting first helper...\n";
std::thread helper1(foo);

std::cout << "starting second helper...\n";
std::thread helper2(bar);

std::cout << "waiting for helpers to finish..." << std::endl;
helper1.join();
helper2.join();

std::cout << "done!\n";
}

(来源:http://en.cppreference.com/w/cpp/thread/thread/join)

我尝试了“g++ -std=c++11 main.cpp”和“g++ main.cpp -std=c++0x”,但我总是遇到以下错误:

main.cpp: In function 'void foo()':
main.cpp:8:10: error: 'std::this_thread' has not been declared
std::this_thread::sleep_for(std::chrono::seconds(1));
^
main.cpp: In function 'void bar()':
main.cpp:14:10: error: 'std::this_thread' has not been declared
std::this_thread::sleep_for(std::chrono::seconds(1));
^
main.cpp: In function 'int main()':
main.cpp:20:5: error: 'thread' is not a member of 'std'
std::thread helper1(foo);
^
main.cpp:23:5: error: 'thread' is not a member of 'std'
std::thread helper2(bar);
^
main.cpp:26:5: error: 'helper1' was not declared in this scope
helper1.join();
^
main.cpp:27:5: error: 'helper2' was not declared in this scope
helper2.join();
^

最佳答案

MinGW 大多没有像 GCC 那样支持 pthreading 或 gthreading 的 glibc 端口。

要解决这个问题,第一个解决方案可以是安装 library of thread headers .另一个解决方案可以使用 GCC 编译器。

关于c++ - 如何使用 MinGW 编译 C++ std::thread 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44384253/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com