<inttypes.h> 中的格式说明符导致跨平台兼容性警告

Format specifier in <inttypes.h> causes warning in cross-platform compatibility

我正在使用库 <inttypes.h> (<stdint.h>) 来实现已使用类型的跨平台兼容性。在我的 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 位 ,但是如果格式说明符更多,那么它也必须更大以便维护连贯性。

PRIu16 用于 打印 uint16_t.

您必须使用 SCNu16 进行 阅读 uint16_t

此外,您必须使用 SCNu32,而不是 PRIu32,才能阅读 uint32_t