C++、mingw 和 clock_gettime 无法编译
C++, mingw and clock_gettime doesn't compile
我在使用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
有谁知道为什么会发生这种情况,知道潜在的解决方案吗?
clock_gettime
不是标准的C或c++函数,因此不能保证它将在非posix系统上可用。
如果你正在编写现代c++,那么你可以使用std::chrono
库来实现高精度计时。
如果你坚持使用2011年以前的库,那么你唯一的选择是time()
,它通常只有一秒的精度,或者任何特定于平台的替代方案。遗憾的是,我对MinGW的了解不够,无法帮助您。
UPDATE:我刚刚用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>