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

。_饼干妹妹 提交于 2019-12-30 04:05:26

问题


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". 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;
}

回答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)




回答2:


If you are running under the Windows operating system, include windows.h header file to your program and change sleep() to Sleep().

The problem would get disappeared.

I hope this helps.



来源:https://stackoverflow.com/questions/8764295/undefined-reference-to-sleep-but-i-did-include-unistd-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!