问题描述
我正在使用库 <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
。