在 32 和 64 平台上使用 sizeof 的 printf:如何以独立于平台的方式处理格式代码? [英] printf with sizeof on 32 vs 64 platforms: how do I handle format code in platform independent manner?

查看:16
本文介绍了在 32 和 64 平台上使用 sizeof 的 printf:如何以独立于平台的方式处理格式代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以打印程序使用的内存量.该行类似于此:

I have some code that prints the amount of memory used by the program. The line is similar to this:

printf("The about of RAM used is %u", anIntVariable*sizeof(double) );

其中 anIntVariable 是表示双精度数组元素数量的 int 变量.无论如何,在 32 位系统上我从来没有遇到任何问题,但在 64 位系统上,我收到一个编译器警告,关于将%u"用于无符号长整数.使用%lu"作为格式代码修复了 64 位上的问题,但导致编译器在 32 位上抱怨,因为类型返回到 unsigned int.我发现实际上,sizeof(double) 在 32 位和 64 位系统上返回不同的值.我找到了一些将代码从 32 位转换 的网页指南,但我宁愿让代码同时适用于两者,而不仅仅是来回转换.

where anIntVariable is an int variable for the number of elements of the double array. Anyhow, on 32-bit systems I never had any problems but on 64-bit systems, I get a compiler warning about using "%u" for a unsigned long integer. Using "%lu" as the format code fixes the problem on 64-bit but causes the compiler to complain on 32-bit because the type is back to unsigned int. I've found that, indeed, sizeof(double) returns a different value on 32 vs 64 bit systems. I've found some webpage guides to convert code from 32 bit to 64 bit But I'd rather have code that works on both instead of just converting back and forth.

如何以独立于平台的方式编写此行?我知道很多方法可以使用预处理器指令来做到这一点,但这似乎是一种黑客行为.当然,我没有意识到有一种优雅的方式.

How do I write this line in a platform independent way? I know many ways I could do it using preprocessor directives but that seems like a hack. Surely there's an elegant way that I'm not realizing.

推荐答案

包含文件中提供了便携式 printf 标识符 inttypes.h此处.

Portable printf identifiers are provided in the include file inttypes.h or here.

此包含文件具有许多适用于您的特定运行时的可移植标识符.对于您的示例,您需要 PRIuPTR,这意味着PRintf I标识符unsigned with size up to a pointer's size".

This include file has many portable identifiers for your specific runtime. For your example, you want PRIuPTR, which means "PRintf Identifier unsigned with size of up to a pointer's size".

您的示例将是:

printf("The amount of RAM used is %" PRIuPTR, anIntVariable*sizeof(double) );

在带有 GCC 4.3 的 64 位 Linux 上的结果(int anIntVariable = 1):

Results on 64bit Linux with GCC 4.3 (int anIntVariable = 1):

$ gcc test.c -m32 -o test && ./test
The amount of RAM used is 8
$ gcc test.c -o test && ./test
The amount of RAM used is 8

为了完整起见,scanf 也有标识符,前缀是 SCN.

For completeness sake, there are identifiers for scanf too, whose prefixes are SCN.

这篇关于在 32 和 64 平台上使用 sizeof 的 printf:如何以独立于平台的方式处理格式代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆