Trying to use clock_gettime (), but getting a lot of "undeclared" errors from time.h

I am trying to measure the running time of a function using clock_gettime() . I include time.h , I added -lrt to the Makefile and added the correct path to the Eclipse CDT. However, when I try to compile, I keep getting errors like this:

 experiments.c: In function 'main': experiments.c:137:2: error: unknown type name 'timespec' timespec time1, time2; ^ experiments.c:139:2: warning: implicit declaration of function 'clock_gettime' [-Wimplicit-function-declaration] clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1); ^ experiments.c:139:16: error: 'CLOCK_PROCESS_CPUTIME_ID' undeclared clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1); 

This happens with any type of CLOCK_ that I am trying to use. I read a lot of questions / answers and tutorials, but could not find something that helps.

In the headers I include:

 #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> 

I'm on Ubuntu 13.10 32 bit and compiling on gcc with the following CFLAGS : -g -Wall -pedantic -std=c99

If I add the flag -D_POSIX_C_SOURCE=199309L , I get error: unknown type name 'timespec' and warnings about using timespec .

This is part of the code, just in case it helps:

 timespec time1, time2; int temp; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1); . . . clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1); /*code stuff*/ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2); 

thanks

+5
source share
1 answer

Putting this and this together, I was able to make it work. I had to add the _POSIX_C_SOURCE macro to make sure that the preprocessor loads library functions correctly, which I did by adding this line before everything mine includes:

 #define _POSIX_C_SOURCE 199309L 

Then I started getting the unknown type name timespec , which was happening because you must explicitly tell the compiler that timespec is a struct . Fixed by writing:

 struct timespec time1, time2; 

instead of timespec time1, time2; .

+3
source

Source: https://habr.com/ru/post/1206304/


All Articles