1

I am working on my Final Project and I need to use the nanosleep function which suspends my program for a specified number of seconds. I tried to test this function first before using it in my actual program I get a compilation error :

test.c:12:3: error: implicit declaration of function 'nanosleep' is invalid in C99 [-Werror,-Wimplicit-function-declaration] nanosleep(t, t);

What's the problem I included time.h and still.. here is my code :

#include<sys/time.h>
#include<stdio.h>

int main(void)
{
     struct timespec t;
     t.tv_sec = 0;
     t.tv_nsec = 1000000000;
     for (int i = 0; i < 30; i++)
     {
         printf("%d\n", i);
         nanosleep(t, t);

     }
}

Note: I tried #include as well

0

According to the man page you also need a Feature Test Macro:

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

nanosleep(): _POSIX_C_SOURCE >= 199309L

see man 7 feature_test_macros for more on that. Pay special attention to:

NOTE: In order to be effective, a feature test macro must be defined before including any header files. This can be done either in the compilation command (cc -DMACRO=value) or by defining the macro within the source code before including any headers.

2
  • do you mean like adding #define _POSIX_C_SOURCE 199309L before my includes ? – A.Emad Dec 23 '16 at 16:20
  • I get it now. Just link in fifteen in pset 4 where he defined the test macro at the top of the includes. Thanks alot – A.Emad Dec 23 '16 at 16:36
0

I just had to include the header and function prototype to clear the warnings.

#include <time.h>
int nanosleep(const struct timespec *req, struct timespec *rem);

This came directly from the SYNOPSIS - https://man7.org/linux/man-pages/man2/nanosleep.2.html

You must log in to answer this question.

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