为什么 _sleep(1000) 不能在 Xcode 中编译?

Why won't _sleep(1000) compile in Xcode?

本文关键字:Xcode 编译 不能 sleep 1000 为什么      更新时间:2023-10-16

我有一个程序应该从10倒计时到0,每次倒计时都应该等待一秒钟,然后使用cin.flush()刷新输出。教授在课堂上演示了这一点,但它运行得很好,当我回到家时,Xcode给了我一个错误,说_sleep(1000)是使用了一个未声明的标识符"_sleep"——在我导入特殊命令时,情况并非如此,它只应该在windows编译器中使用_sleep。

简而言之,这需要在windows和mac编译器中进行编译,而我应该通过这些编译器定义来完成。但由于某种原因,Xcode一直试图告诉我这是错误的。

#ifdef GPP
#include <unistd.h>
#else
#include <cstdlib>
#endif

int main()
{
    for (int timer = 10; timer >= 0; timer--)
    {
        cout << timer;
        cout.flush();
        //compiler functions
        #ifdef GPP
        Sleep(1); //One second to sleep on GPP compilers
        #else
        _sleep(1000);//On windows 1000ms sleep time
        #endif
        cout << 'r';
    }
}

睡眠和变体是不可移植的,它们是特定于操作系统的。这就是我们使用标准的原因

std::this_thread::sleep_for (std::chrono::milliseconds(your time here));

您在任何地方定义了GPP吗?如果没有,那么代码将使用sleep(1000),它是windows特有的,不会在mac上工作。例如,如果像这样编译,它应该可以工作:

g++ -DGPP

但你仍然需要将"睡眠"改为"睡眠",因为也没有"睡眠"功能。

#ifdef GPP                                                                      
#include <unistd.h>                                                             
#else                                                                           
#include <cstdlib>                                                              
#endif                                                                          
#include <iostream>                                                             
using namespace std;                                                            
int main()                                                                      
{                                                                               
    for (int timer = 10; timer >= 0; timer--)                                   
    {                                                                           
        cout << timer;                                                          
        cout.flush();                                                           
        //compiler functions                                                    
#ifdef GPP                                                                      
        sleep(1); //One second to sleep on GPP compilers                        
#else                                                                           
        _sleep(1000);//On windows 1000ms sleep time                             
#endif                                                                          
        cout << 'r';                                                           
    }                                                                           
}