【问题标题】:std::this_thread::sleep_for doesn't exist - Windows 10 g++std::this_thread::sleep_for 不存在 - Windows 10 g++
【发布时间】:2021-12-25 07:20:33
【问题描述】:

我目前正在运行一个在线执行完美的测试程序 (replit.com),但是当我在本地运行它时(在带有 gcc 和 g++ 的 Windows 10 上)我收到一个错误:

test.cpp: In function 'int main()':
test.cpp:18:8: error: 'std::this_thread' has not been declared
   std::this_thread::sleep_for(std::chrono::milliseconds(time));

这是我的程序:

#include <iostream>
#include <thread>
#include <chrono>
#include <random>
#include <string>

int randomInt (int MIN, int MAX) {
    std::random_device rd;
    std::default_random_engine eng(rd());
    std::uniform_int_distribution<int> distr(MIN, MAX);
    return distr(eng);
}

int main() {
    int loop = 20;
    for (int i = 0; i < loop; i++) {
        int time = randomInt(10, 100);
        std::this_thread::sleep_for(std::chrono::milliseconds(time));
    }

    return 0;
}

为什么会这样?

【问题讨论】:

  • g++ 的版本是什么以及如何调用它?
  • 您需要将-std=c++11(或更新版本)作为命令行参数传递给g++。许多版本的 g++ 默认使用旧版本的语言标准。如果不传递该参数,您应该得到更多的错误,而不仅仅是关于 this_thread
  • @selbie 我运行了这个命令:g++ test.cpp -std=c++11 -o test 还是不行
  • @S.M.我正在使用 g++ 6.3。命令:g++ test.cpp -std=c++11 -o test
  • 不能reproduce

标签: c++ windows multithreading


【解决方案1】:

我回到 replit.com 看看他们在做什么来编译程序。显然他们使用了-pthreads 开关:

g++ -pthread -std=c++17 -o main main.cpp

现在对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 2020-10-19
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2018-09-07
    • 1970-01-01
    相关资源
    最近更新 更多