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

使用gcc 4.3.3加-std=c99编译时出现gmtime_r隐式声明警告

问题:gcc 4.3.3编译C99代码时gmtime_r出现隐式声明警告

我使用Ubuntu 4.3.3-5ubuntu4版本的gcc 4.3.3编译包含nan()、swprintf()等C99特性的代码,添加-std=c99参数后解决了部分编译问题,但出现警告:warning: implicit declaration of function ‘gmtime_r’。我疑惑gmtime_r是否从C99标准中被移除?

测试代码:

#include <math.h>
#include <time.h>

int
main(int argc, char **argv)
{
    double x;
    time_t t;
    struct tm tm;

    x = nan("0");
    t = time(NULL);
    gmtime_r(&t, &tm);

    return 0;
}

编译结果:

$ cc --version
cc (Ubuntu 4.3.3-5ubuntu4) 4.3.3
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ cc -c foo.c
foo.c: In function ‘main’:
foo.c:12: warning: incompatible implicit declaration of built-in function ‘nan’

$ cc -c -std=c99 foo.c
foo.c: In function ‘main’:
foo.c:14: warning: implicit declaration of function ‘gmtime_r’

解答

  • gmtime_r不属于C99标准
    gmtime_r是POSIX标准定义的线程安全函数,C99标准仅包含线程不安全的gmtime(),它从来没有被纳入C99,不存在“被移除”的说法。

  • 警告产生的原因
    当指定-std=c99参数时,gcc会严格遵循C99标准进行编译,此时系统头文件会隐藏POSIX扩展相关的内容,time.h中不会提供gmtime_r的函数声明,编译器找不到原型,就会触发隐式声明警告。

  • 解决方法
    有两种可行方案:

    1. 保留-std=c99,同时定义POSIX宏,让头文件暴露扩展函数声明:
      cc -c -std=c99 -D_POSIX_C_SOURCE=200112L foo.c
      
    2. 改用gcc的扩展标准gnu99,它默认支持C99语法且包含POSIX特性:
      cc -c -std=gnu99 foo.c
      
      两种方式都能消除gmtime_r的警告,同时正常编译nan()这类C99函数。
  • 补充:关于nan()的警告
    不加-std=c99时,gcc默认使用GNU89标准,nan()是C99新增函数,此时math.h中没有它的原型,因此编译器报隐式声明警告;添加-std=c99后,头文件会提供nan()的声明,警告自然消失。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 15:27:11