PRID64干啥的

http://blog.163.com/guixl_001/blog/static/4176410420121021111117987/

nt64_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:

  1. /* The ISO C99 standard specifies that these macros must only be
  2.    defined if explicitly requested.  */ 
  3. #if !defined __cplusplus || defined __STDC_FORMAT_MACROS 
  4.  
  5. # if __WORDSIZE == 64 
  6. #  define __PRI64_PREFIX    "l" 
  7. #  define __PRIPTR_PREFIX   "l" 
  8. # else 
  9. #  define __PRI64_PREFIX    "ll" 
  10. #  define __PRIPTR_PREFIX 
  11. # endif 
  12.  
  13. /* Macros for printing format specifiers.  */ 
  14.  
  15. /* Decimal notation.  */ 
  16. # define PRId8      "d" 
  17. # define PRId16     "d" 
  18. # define PRId32     "d" 
  19. # define PRId64     __PRI64_PREFIX "d" 
原来这个是定义给c用的,C++要用它,就要定义一个__STDC_FORMAT_MACROS宏显示打开它。

  1. /* test_int64.cpp
  2. g++ -D__STDC_FORMAT_MACROS -o test_int64 -g -O0 test_int64.cpp
  3. */ 
  4. #include <stdio.h> 
  5. #include <inttypes.h> 
  6.  
  7. int main(int argc, char** argv){ 
  8.     int64_t value = 0xFFFFFFFFFFFF; 
  9.     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,还可以使用更好的方式:

  1. /* test_int64_1.cpp
  2. g++ -o test_int64_1 -g -O0 test_int64_1.cpp
  3. */ 
  4. #include <stdio.h> 
  5. #include <cinttypes> 
  6. using namespace std; 
  7.  
  8. int main(int argc, char** argv){ 
  9.     int64_t value = 0xFFFFFFFFFFFF; 
  10.     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++编译,可以使用后者,否则可以用前者直接定义宏

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值