Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get in my timespec-array the error "array type has incomplete element type"?

Tags:

c

I got a problem with my C-Code in Eclipse. To be specific my sleep-method does produce an error in the line where the timespec is stated. May you guys can tell me what I did wrong? Here's the code:

void sleep(double time) {
    nanosleep(
        (struct timespec[]) { {time,((time -((time_t)time)) * 1000000000)}},
        NULL);
}
like image 220
WolfgangRabenstein Avatar asked Dec 14 '25 06:12

WolfgangRabenstein


1 Answers

You need to include the header file which defines the type timespec. Either:

  • You forgot to include the header file or
  • You merely forward declared the type.

Second seems the most likely cause of error. Since you are creating an array, the compiler needs to know the definition of timespec as it needs to allocate that much memory for the array.


The problem is that struct timespec and nanosleep() are not defined in the C standard. They are provided by POSIX standard. It seems you are compiling with -std=c99 or so which makes your compiler to strictly adhere to the C99 standard and hence report errors. To be able to compile these POSIX constructs you will have to explicitly enable them.

Compilation with std=c99

Compilation after enabling POSIX definitions:

#if __STDC_VERSION__ >= 199901L
# define _XOPEN_SOURCE 600
#else
# define _XOPEN_SOURCE 500
#endif /* __STDC_VERSION__ */

#include <time.h>

int main()
{
    double time = 0.1;

    nanosleep((struct timespec[]) { {time, ((time - ((time_t)time)) *
               1000000000)}}, NULL);

    return 0;
}  

__STDC_VERSION__ checks if the compiler you are using is c99 & depending on the compiler it enables the POSIX definitions.
_XOPEN_SOURCE defines which version of POSIX you want to refer to. Select the definition as per the POSIX version you use. 600 refers to POSIX 2004 while 500 refers to POSIX 1995.

like image 84
Alok Save Avatar answered Dec 16 '25 22:12

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!