Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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". 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;
}
like image 556
Mengfei Murphy Avatar asked Jan 06 '12 20:01

Mengfei Murphy


2 Answers

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)

like image 77
kwadr4tic Avatar answered Sep 20 '22 13:09

kwadr4tic


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.

like image 22
K Palaniswamy Avatar answered Sep 16 '22 13:09

K Palaniswamy