【问题标题】:Sleep() is undefined but it knows _sleep() exists and says to use Sleep() instead? c++Sleep() 未定义,但它知道 _sleep() 存在并说要使用 Sleep() 代替? C++
【发布时间】:2019-11-12 17:53:56
【问题描述】:

我需要使用某种形式的 Sleep() 来让用户跟上程序的速度并观察屏幕上的东西。我在使用任何使程序停止一小段时间的命令时遇到问题,但至少现在 Sleep() 似乎是我最好的选择。我已经包含 stdlib.h 并接受 _sleep() 并且当我运行程序时它说使用 Sleep() 因为它已被新库取代。并且在 stdlib.h Sleep() 中也确实存在。我遇到了一个完全的障碍,非常感谢任何建议! (与 2017 的错误不同,因为我使用的是 2019)

代码:

void startGame() {
    //bool flag = true;
    for (int a = 0; a < 10; a++) {
        screenUpdate();
        for (int i = 0; i < 4; i++) {
            rowsShown[i]++;
        }
        Sleep(500); // this comes out with an error
        //to show what the other one does
        _sleep(500);
    }
}

错误:

Severity    Code    Description Project File    Line    Suppression State
Error (active)  E0020   identifier "Sleep" is undefined 

Severity    Code    Description Project File    Line    Suppression State
Error   C4996    '_sleep': This function or variable has been superceded by newer library or operating system functionality. Consider using Sleep instead. See online help for details.

【问题讨论】:

标签: c++ winapi visual-c++


【解决方案1】:

建议包含windows.h (#include &lt;windows.h&gt;) 而不是只包含synchapi.h,因为

有很多子头文件是自动生成的 包含在 windows.h 中。其中许多文件不能简单地包含在内 由于依赖关系,它们本身(它们不是独立的)。

因此,如果您只包含synchapi.h,您可能会得到比其他identifiers are undefined 更多的E0020 错误。

Sleep 功能的使用方法可以参考“Using Thread Local Storage”示例。

如果您想要使用更小的头文件更快地构建,您可以通过排除一些不太常见的 API 声明来减小 Windows 头文件的大小。更多详细信息,请访问“Using the Windows Headers”。

【讨论】:

  • 最好只使用std::this_thread::sleep_for(std::chrono::milliseconds{500})。更便携,不需要包含windows.h
猜你喜欢
  • 2018-08-30
  • 2010-09-20
  • 2015-11-16
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 2015-09-18
  • 2014-12-28
相关资源
最近更新 更多