Linux 关于 printf() long unsigned int 和 uint32_t 的编译器警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4961115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compiler warning about printf() long unsigned int and uint32_t
提问by pr1268
In my C code, I'm fprintf
ing a "%lu"
and giving a uint32_t
for the corresponding field. But, when I compile with -Wall
in GCC (ver. 4.2.4), I get the following warning:
在我的 C 代码中,我fprintf
输入了 a"%lu"
并uint32_t
为相应的字段给出了 a 。但是,当我-Wall
在 GCC (ver. 4.2.4) 中编译时,我收到以下警告:
writeresults.c:16: warning: format '%4lu' expects type 'long unsigned int', but argument 2 has type
`uint32_t'
Aren't a uint32_t
and long unsigned int
the same thing on 32-bit architectures? Can this warning be avoided without eliminating the -Wall
compiler switch or using a typecast (and if so, how)?
是不是uint32_t
和long unsigned int
32位架构是一回事吗?在不消除-Wall
编译器开关或使用类型转换的情况下是否可以避免此警告(如果是,如何)?
Yes, I'm still using a 32-bit computer/arch/OS/compiler (too poor at the moment to afford new 64-bit HW). Thanks!
是的,我仍在使用 32 位计算机/架构/操作系统/编译器(目前太穷,无法负担新的 64 位硬件)。谢谢!
采纳答案by Conrad Meyer
uint32_t
on x86 Linux with GCC is just unsigned int
. So use fprintf(stream, "%4u", ...)
(unsigned int) or better yet, fprintf(stream, "%4" PRIu32, ...)
(the inttypes.h
printf-string specifier for uint32_t
).
uint32_t
在带有 GCC 的 x86 Linux 上只是unsigned int
. 因此,请使用fprintf(stream, "%4u", ...)
(unsigned int) 或更好的方法,fprintf(stream, "%4" PRIu32, ...)
(用于 的inttypes.h
printf 字符串说明符uint32_t
)。
The latter will definitely eliminate the compiler warning / error, and, additionally, is cross-platform.
后者肯定会消除编译器警告/错误,此外,它是跨平台的。
回答by gparent
"long int" and "int" are different types in C++. You might be looking for the "u" format, which stands for "unsigned int". Of course, this depends on what "uint32_t" is a typedef for on your compiler.
“long int”和“int”在 C++ 中是不同的类型。您可能正在寻找“u”格式,它代表“unsigned int”。当然,这取决于编译器上的“uint32_t”是什么类型的定义。
回答by William Pursell
The easiest way to reliably suppress the warning is with a cast:
可靠地抑制警告的最简单方法是使用强制转换:
printf( "%lu", ( unsigned long )x );