起因
之所以写这篇文章,是因为最近在使用类似printf
之类的函数格式化uint64_t
类型数据的时候,由于uint64_t
在32位和64位平台下定义类型不一样,编译器会有Wformat
警告。比如,以下代码:
uint64_t x = UINT64_MAX;
printf("x = %llu\n", x);
在64位平台下编译会有类似如下的警告:
warning: format ‘%llu’ expects argument of type ‘long long unsigned int’, but argument 2 has type ‘uint64_t {aka long unsigned int}’ [-Wformat=]
这是因为,uint64_t
在32位平台下定义的是unsigned long long
使用%llu
格式化,而64位平台下定义的是unsigned long int
,需要使用%lu
格式化。
解决方案
为了解决这问题,可以使用PRIu64
可实现uint64_t
的跨平台打印。C++中需包含#include <cinttypes>
,写法如下:
uint64_t x = UINT64_MAX;
printf("x = %" PRIu64".\n", x);
第二行代码的写法就触及到我C语法知识盲区了。平时是写C++的,在写代码的时候,除却为了支持跨平台不得不做的一些宏定义,我是很少使用宏的。