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

查看:93
本文介绍了在32 vs 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位问题,但由于类型返回到unsigned int,导致编译器在32位上抱怨。我发现,在32位和64位系统上,sizeof(double)确实返回了不同的值。我已经找到了一些网页指南,可以将代码从32位转换为64位,但我宁愿有可以同时使用的代码,而不仅仅是来回转换。

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.

推荐答案

包含文件 inttypes.h

此包含文件具有用于您特定运行时的许多可移植标识符。对于您的示例,您需要PRIuPTR,这意味着 PR intf 标识符 u ,其大小最大为指针的大小。

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 vs 64平台上使用sizeof的printf:如何以平台无关的方式处理格式代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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