0

I am using this function usleep() which is suppose to stop any operation for several seconds. Any way I get this error while trying to compile my code

stream.c:28:4: error: implicit declaration of function 'usleep' is invalid in C99 [-Werror,-Wimplicit-function-declaration]

I know that this means that I should include the library which contains this function and I read about in the GNU manual and double checked the library that contains this function and "included" the library in my code. Still I get the same error.In addition I installed the unistd.h on my system. Any ideas why might that be happening ?

here is my code (usleep is in the forloop)

 // standard libraries
 #include <unistd.h>
 #include <stdio.h>
 #include <stdlib.h>

//mpg library 
#include "mpg.h"


// main function
int main(void)
{
   FILE* media = fopen("live.mp3", "r");
   if(media == NULL)
   {
       printf("Couldn't read file\n");
       return -1;
   } 
   MPEGTAG2* mp3_tag = malloc(sizeof(mp3_tag));

   mp3Header(media, mp3_tag);
   while(feof(media) == 0)
   {
      int ms;
      int nbits;
      frameInfo(media, &ms, &nbits);
      size_t nbytes = nbits / 8;
      int rate = ms / nbytes;
      for(int i = 0; i < nbytes; i++)
      {
          printf("%d seconds\n", rate);
          usleep(rate);
      }
      fseek(media, nbytes, SEEK_CUR);
  }
  free(mp3_tag);

}
2
  • Not an answer to your problem, but I'll say it: usleep() is obsolete. You shouldn't use it! Use nanosleep() instead. Commented Dec 9, 2016 at 22:50
  • I guess nanosleep will be more precise in that case but I was just wondering
    – A.Emad
    Commented Dec 9, 2016 at 23:08

1 Answer 1

1

usleep() is obsolete, but I think the solution is to add this macro atop your code to make it work without warnings:

#define _XOPEN_SOURCE 500

Like this:

#define _XOPEN_SOURCE 500

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

See:

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
usleep():
Since glibc 2.12:
_BSD_SOURCE ||
    (_XOPEN_SOURCE >= 500 ||
        _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) &&
    !(_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700)
Before glibc 2.12:
_BSD_SOURCE || _XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED

on http://man7.org/linux/man-pages/man3/usleep.3.html

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .