You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用gettimeofday64函数出现编译错误的原因咨询

为什么使用gettimeofday64()会出现编译错误?

问题描述

我尝试用gettimeofday64()替代gettimeofday()函数,编写了如下代码:

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

int main () {
   struct timeval64 tim;
   int ret = gettimeofday64(&tim, NULL);

   printf("Ret = %d\n", ret);

return 0;
}

编译时出现以下错误:

day.cpp: In function ‘int main()’:
day.cpp:5: error: aggregate ‘timeval64 tim’ has incomplete type and cannot be defined
day.cpp:6: error: ‘gettimeofday64’ was not declared in this scope

但使用gettimeofday()并包含<sys/time.h>头文件时,代码可正常运行。

原因分析与解决方法

  • gettimeofday64()并非标准接口,需手动启用:gettimeofday64()和struct timeval64是Linux/glibc为解决2038年时间溢出问题推出的64位时间扩展接口,不属于标准C或POSIX规范,默认情况下头文件不会暴露它们的声明。要使用这些接口,你需要:

    1. 包含正确的头文件:必须包含<sys/time.h>(和gettimeofday()的依赖头文件一致),而不是仅<time.h>。
    2. 定义特定宏开启扩展:在包含<sys/time.h>之前,必须定义_TIME_BITS=64宏,部分环境还需要搭配_FILE_OFFSET_BITS=64;如果是老版本glibc,可能还得加上_GNU_SOURCE宏来启用GNU扩展特性,否则编译器找不到这些接口的声明。
  • 更兼容的替代方案:在较新的glibc版本中,完全没必要直接调用gettimeofday64()。只要在代码开头定义_TIME_BITS=64,直接使用标准的gettimeofday()和struct timeval即可——此时struct timeval会被自动映射为64位的timeval64,内部实现和gettimeofday64()一致,还能保证更好的代码兼容性。

修正后的示例代码

方案一:用标准接口配合64位时间宏(推荐)

#define _TIME_BITS 64
#define _FILE_OFFSET_BITS 64
#include <sys/time.h>
#include <stdio.h>

int main () {
    struct timeval tim; // 定义宏后自动转为64位结构体
    int ret = gettimeofday(&tim, NULL);

    printf("Ret = %d\n", ret);
    return 0;
}

方案二:直接调用gettimeofday64()

#define _GNU_SOURCE
#define _TIME_BITS 64
#include <sys/time.h>
#include <stdio.h>

int main () {
    struct timeval64 tim;
    int ret = gettimeofday64(&tim, NULL);

    printf("Ret = %d\n", ret);
    return 0;
}

内容的提问来源于stack exchange,提问作者Savita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 22:07:32