【问题标题】:Format specifier in <inttypes.h> causes warning in cross-platform compatibility<inttypes.h> 中的格式说明符导致跨平台兼容性警告
【发布时间】:2021-09-06 23:38:31
【问题描述】:

我正在使用库 &lt;inttypes.h&gt; (&lt;stdint.h&gt;) 以实现跨平台的无符号类型兼容性。在我的 MacOSX 上使用 -Wall 选项编译时不会出现警告,而在 Ubuntu 20.04 上我得到

mvmpi.c: In function ‘main’:
mvmpi.c:33:9: warning: format ‘%u’ expects argument of type ‘unsigned int *’, but argument 6 has type ‘uint16_t *’ {aka ‘short unsigned int *’} [-Wformat=]
   33 |         "%"PRIu32"%"PRIu32"%lf%"PRIu16, &N, &M, &L, &SN) != EOF) {
      |         ^~~                                         ~~~
      |                                                     |
      |                                                     uint16_t * {aka short unsigned int *}
In file included from stdbasic.h:33,
                 from mvmpilib.h:8,
                 from mvmpi.c:4:
/usr/include/inttypes.h:103:19: note: format string is defined here
  103 | # define PRIu16  "u"

格式化抱怨变量SN被声明为uint16_t变量,然后它使用"%"PRIu16格式说明符,但令人惊讶的是PRIu16在C源代码库中定义为unsigned int,而uint16_t 将(定期)short unsigned int

这里发生了什么?如何解决和保持跨平台兼容性? 当然,文档中的uint16_t 是用至少 16 位定义的,但如果格式说明符更多,那么它也必须更大以保持连贯性。

【问题讨论】:

  • "当然 uint16_t 来自文档的定义是至少 16 位" No. uintN_t 被定义为完全 N 位. (N15707.20.1.1 精确宽度整数类型)

标签: c compiler-warnings format-specifiers stdint


【解决方案1】:

PRIu16 用于打印 uint16_t

您必须使用SCNu16阅读 uint16_t

另外你必须使用SCNu32,而不是PRIu32,来阅读uint32_t

【讨论】:

  • unsigned short int 将被提升为intunsigned int,当它被传递给printf() 进行打印时。明确指定 short 部分可能会在传递错误数据时提高安全性,但不指定不会影响正确使用时的行为。
  • 真可惜,对不起,先生,感谢您的回复。顺便说一句,另一个PRIu32 没有出现同样的错误......这以某种方式触发了我的大脑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-07-28
  • 1970-01-01
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
  • 2018-09-16
  • 1970-01-01
相关资源
最近更新 更多