What is the proper #include for the function 'sleep()'?

CPosixSleep

C Problem Overview


I am using the Big Nerd Ranch book Objective-C Programming, and it starts out by having us write in C in the first few chapters. In one of my programs it has me create, I use the sleep function. In the book it told me to put #include <stdlib.h> under the #include <stdio.h> part. This is supposed to get rid of the warning that says "Implicit declaration of function 'sleep' is invalid in C99". But for some reason after I put #include <stdlib.h>, the warning does not go away.. This problem does not stop the program from running fine, but I was just curious on which #include I needed to use!

C Solutions


Solution 1 - C

The sleep man page says it is declared in <unistd.h>.

Synopsis:

#include <unistd.h>

> unsigned int sleep(unsigned int seconds);

Solution 2 - C

sleep is a non-standard function.

  • On UNIX, you shall include <unistd.h>.
  • On MS-Windows, Sleep is rather from <windows.h>.

In every case, check the documentation.

Solution 3 - C

this is what I use for a cross-platform code:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

int main()
{
  pollingDelay = 100
  //do stuff

  //sleep:
  #ifdef _WIN32
  Sleep(pollingDelay);
  #else
  usleep(pollingDelay*1000);  /* sleep for 100 milliSeconds */
  #endif

  //do stuff again
  return 0;
}

Solution 4 - C

>What is the proper #include for the function 'sleep()'?

sleep() isn't Standard C, but POSIX so it should be:

#include <unistd.h>

Solution 5 - C

sleep(3) is in unistd.h, not stdlib.h. Type man 3 sleep on your command line to confirm for your machine, but I presume you're on a Mac since you're learning Objective-C, and on a Mac, you need unistd.h.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontrludtView Question on Stackoverflow
Solution 1 - CsimoncView Answer on Stackoverflow
Solution 2 - Cmd5View Answer on Stackoverflow
Solution 3 - CRomain VIOLLETTEView Answer on Stackoverflow
Solution 4 - CalkView Answer on Stackoverflow
Solution 5 - CCarl NorumView Answer on Stackoverflow