C ++,mingw和clock_gettime无法编译

时间:2013-04-01 15:56:07

标签: c++ time timer mingw

使用minGW的g ++。exe编译一些Linux C ++代码时遇到了一些困难。 具体来说,它无法理解此代码:

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

我添加了必要的头文件

 #include <ctime>

编译错误是:

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

有人知道为什么会这样,并且知道潜在的解决方法吗?

2 个答案:

答案 0 :(得分:6)

clock_gettime不是标准的C或C ++函数,因此无法保证它在非POSIX系统上可用。

如果您正在编写现代C ++,那么您可以使用std::chrono库进行高精度计时。

如果您遇到2011年之前的库,那么您唯一的选择是time(),通常只有一秒的精度,或者任何特定于平台的替代品都可用。不幸的是,我不太了解MinGW对你的帮助。

答案 1 :(得分:1)

更新:我刚刚使用MinGW尝试了以下内容,但它无效。正如另一个答案所说,POSIX功能不一定在Windows下可用。这个答案并没有解决OP的问题,但它可能对其他系统的用户有用。

clock_gettime由POSIX定义,而不是由语言标准定义。

我系统上的手册页(Ubuntu)说:

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

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

尝试添加

#define _POSIX_C_SOURCE 199309L
#include <ctime>

之前

相关问题