简体   繁体   English

未定义的参考“睡眠”,但我确实包括<unistd.h>

[英]Undefined reference to “sleep” but I did include <unistd.h>

Well, this must be a silly one. 嗯,这一定是个傻瓜。 Here below is a can-not-be-simpler code in C. It can not compile saying "undefined reference to sleep". 下面是C中不可能更简单的代码。它不能编译说“未定义的睡眠引用”。 But I think I include all system header I need... 但我想我包括我需要的所有系统头...

#include <stdio.h>
#include <unistd.h>
int main()
{
    printf("Test starts.\n");
    sleep(1);
    printf("Test ends.\n");

    return 1;
}

Try this at the top: 在顶部试试这个:

#ifdef __unix__
# include <unistd.h>
#elif defined _WIN32
# include <windows.h>
#define sleep(x) Sleep(1000 * (x))
#endif

This code will allow you to use two different functions under the same name, that do quite the same thing. 此代码允许您使用相同名称下的两个不同功能,这些功能完全相同。 And it compiles under different platforms. 它在不同平台下编译。

Also, parenthesizing the (x) argument ensures that the delay is right even if someone calls it like this sleep(10+10) 另外,括号化(x)参数确保延迟是正确的,即使有人像这个sleep(10+10)一样调用它sleep(10+10)

If you are running under the Windows operating system, include windows.h header file to your program and change sleep() to Sleep() . 如果您在Windows操作系统下运行,请将windows.h头文件包含到您的程序中,并将sleep()更改为Sleep()

The problem would get disappeared. 问题会消失。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM