Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, mingw and clock_gettime doesn't compile

I'm having quite a bit of difficulty compiling some Linux C++ code using g++.exe from minGW. Specifically, it is unable to understand this code:

  struct timespec now;
  clock_gettime(CLOCK_REALTIME,&now);

I have added necessary header file

 #include <ctime>

The compile error is:

error: aggregate 'special_time2()::timespec now' has incomplete type and cannot be defined
error: 'CLOCK_REALTIME' was not declared in this scope
error: 'clock_gettime' was not declared in this scope

Does anybody know why this is happen and know of a potential workaround?

like image 673
user788171 Avatar asked Apr 01 '13 15:04

user788171


2 Answers

clock_gettime is not a standard C or C++ function, so there's no guarantee that it will be available on non-POSIX systems.

If you're writing modern C++, then you could use the std::chrono library for high-precision timing.

If you're stuck with a pre-2011 library, then your only options are time(), which usually only has a precision of one second, or whatever platform-specific alternatives are available. Unfortunately, I don't know enough about MinGW to help you with that.

like image 89
Mike Seymour Avatar answered Nov 11 '22 12:11

Mike Seymour


UPDATE: I just tried the below with MinGW, and it didn't work. As the other answer says, POSIX functions will not necessarily be available under Windows. This answer does not solve the OP's problem, but it might be useful for users of other systems.

clock_gettime is defined by POSIX, not by the language standard.

The man page on my system (Ubuntu) says:

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

   clock_getres(), clock_gettime(), clock_settime():
          _POSIX_C_SOURCE >= 199309L

Try adding

#define _POSIX_C_SOURCE 199309L

before the #include <ctime>

like image 1
Keith Thompson Avatar answered Nov 11 '22 13:11

Keith Thompson