博客专栏

EEPW首页 > 博客 > C++中正确使用PRId64

C++中正确使用PRId64

发布人:电子禅石 时间:2022-06-17 来源:工程师 发布文章
随笔 - 74  文章 - 181  评论 - 37  阅读 - 57万
转:C++中正确使用PRId64及__STDC_FORMAT_MACROS宏

int64_t用来表示64位整数,在32位系统中是long long int,在64位系统中是long int,所以打印int64_t的格式化方法是:

  1. printf("%ld", value); // 64bit OS

  2. printf("%lld", value); // 32bit OS

当然有跨平台的方法:

  1. #include <inttypes.h>

  2. printf("%" PRId64 "\n", value); 

  3. // 相当于64位的:

  4. printf("%" "ld" "\n", value); 

  5. // 或32位的:

  6. printf("%" "lld" "\n", value); 

其中,printf("abc" "def" “ghi")这样写多个字符串是没有问题的。

但是,死活都编译不过,错误是:error: expected ‘)’ before ‘PRId64’

找了一下这个宏的定义,/usr/include/inttypes.h:

复制代码
/* The ISO C99 standard specifies that these macros must only be
   defined if explicitly requested.  */#if !defined __cplusplus || defined __STDC_FORMAT_MACROS# if __WORDSIZE == 64#  define __PRI64_PREFIX    "l"#  define __PRIPTR_PREFIX    "l"# else#  define __PRI64_PREFIX    "ll"#  define __PRIPTR_PREFIX
# endif/* Macros for printing format specifiers.  *//* Decimal notation.  */# define PRId8        "d"# define PRId16        "d"# define PRId32        "d"# define PRId64        __PRI64_PREFIX "d"
复制代码

原来这个是定义给c用的,C++要用它,就要定义一个__STDC_FORMAT_MACROS宏显示打开它。

编译并执行:

g++ -D__STDC_FORMAT_MACROS -o test_int64 -g -O0 test_int64.cpp

./test_int64

int64_t=281474976710655, sizeof(int64_t)=8

对于C++新标准-std=c++0x,还可以使用更好的方式:

复制代码
/* test_int64_1.cpp 
g++ -o test_int64_1 -g -O0 test_int64_1.cpp*/#include <stdio.h>#include <cinttypes>using namespace std;int main(int argc, char** argv){
    int64_t value = 0xFFFFFFFFFFFF;
    printf("int64_t=%"PRId64", sizeof(int64_t)=%d\n", value, sizeof(int64_t));
}
复制代码

编译并执行:

g++ -D__STDC_FORMAT_MACROS -o test_int64 -g -O0 test_int64.cpp

./test_int64

int64_t=281474976710655, sizeof(int64_t)=8

对于C++新标准-std=c++0x,还可以使用更好的方式:

复制代码
/* test_int64_1.cpp 
g++ -o test_int64_1 -g -O0 test_int64_1.cpp*/#include <stdio.h>#include <cinttypes>using namespace std;int main(int argc, char** argv){
    int64_t value = 0xFFFFFFFFFFFF;
    printf("int64_t=%"PRId64", sizeof(int64_t)=%d\n", value, sizeof(int64_t));
}
复制代码

不用定义那个宏了,编译和执行:

g++ -o test_int64_1 -g -O0 test_int64_1.cpp -std=c++0x

./test_int64_1

int64_t=281474976710655, sizeof(int64_t)=8

当然得指定一个新的参数:-std=c++0x,否则会报错“#error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options.”

若能使用较新的g++编译,可以使用后者,否则可以用前者直接定义宏。


*博客内容为网友个人发布,仅代表博主个人观点,如有侵权请联系工作人员删除。



关键词: C++

相关推荐

技术专区

关闭