【问题标题】:warning: format '%06d' expects type 'int', but argument 5 has type '__suseconds_t'警告:格式“%06d”需要类型“int”,但参数 5 的类型为“__suseconds_t”
【发布时间】:2014-08-20 14:49:04
【问题描述】:

我正在使用此代码:

struct timeval tv;
time_t nowtime;
struct tm *nowtm;
char tmbuf[64], buf[64];

gettimeofday(&tv, NULL);
nowtime = tv.tv_sec;
nowtm = localtime(&nowtime);
strftime(tmbuf, sizeof tmbuf, "%Y-%m-%d %H:%M:%S", nowtm);
snprintf(buf, sizeof buf, "%s.%06d", tmbuf, tv.tv_usec);

来自这个 SO 答案:

https://stackoverflow.com/a/2409054/997112

以可读的格式打印一个 struct timeval。但是,我收到此编译器警告:

warning: format '%06d' expects type 'int', but argument 5 has type '__suseconds_t'

有人可以帮忙吗?

【问题讨论】:

  • 非常自我解释:tv_usec 结构的tv 成员是__suseconds_t 类型。但是,这是一个 long 的 typedef,因此您可以使用 printf 将其显示为 long 数字:将 %06d 替换为 %06ld
  • @LoveMetal 好吧,我想知道为什么有这么多赞成票的答案会有问题。这是因为我使用的系统吗?
  • 嗯...我也想知道 xD。尝试一下long,它通常可以解决一个问题。
  • @LoveMetal 成功了!作为答案,我会接受。

标签: c timeval


【解决方案1】:

编译器发出警告,因为 printf 预期的类型 - int 与参数 - long (这是 __suseconds_t 的类型)不同。只要intlong 的大小相同(32 位或64 位),您的代码就可以在许多当前系统上运行。

因为有 系统不是这种情况(例如 int 32 位,long 64 位),为了更好的可移植性,您应该将值转换为 printf 期望的实际类型:

snprintf(buf, sizeof buf, "%s.%06ld", tmbuf, (long) tv.tv_usec);

由于tv.tv_usec 的值始终小于一百万,因此在具有至少 32 位 int 的系统上,"%06d" 和强制转换为 int 也可以,但我更愿意使用 long。

顺便说一句,警告指出了这些天使用的所有类型定义的问题。如果消息提到long 而不是__suseconds_t,我认为相对初学者可能有更好的机会理解实际问题。 clang 编译器实际上是这样做的:"'__suseconds_t' (aka 'long')"

【讨论】:

    【解决方案2】:

    struct tv 结构的tv_usec 成员是__suseconds_t 数据类型,它是long 的类型定义。您可以使用%06ld 而不是%06d 来显示它。

    而且似乎转换为long 会更好,至少在可移植性问题上是这样。

    【讨论】:

      猜你喜欢
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多