Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to use clock_gettime(), but getting plenty of "undeclared" errors from time.h [duplicate]

Tags:

c

time

libraries

I am trying to measure the running time of a function using clock_gettime(). I am including time.h, I added -lrt to the Makefile, and added the right path on Eclipse CDT. However, when I try to compile I keep getting these kinds of errors:

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_ I try to use. I've been reading plenty of questions/answers and tutorials but haven't been able to find something that helps.

The headers I'm including are:

#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 the 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

like image 377
Francisca Concha-Ramírez Avatar asked Nov 05 '14 23:11

Francisca Concha-Ramírez


1 Answers

Putting this and this answers together I was able to make it work. I had to add the _POSIX_C_SOURCE macro, to make sure the preprocessor was getting the library features correctly, which I did by adding this line before all my includes:

#define _POSIX_C_SOURCE 199309L

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

struct timespec time1, time2; 

instead of just timespec time1, time2;.

like image 81
Francisca Concha-Ramírez Avatar answered Oct 16 '22 23:10

Francisca Concha-Ramírez