为什么我可以在32位而不是64位编译它?

时间:2011-02-14 03:09:03

标签: c

user@user:~/langs/c$ cat 3264int.c 
#include <stdio.h>
int main(){
        long z; 
    printf("Long int size is %d bytes long!\n", sizeof(z)); 

    return 0;
}
user@user:~/langs/c$ cat 3264int.c ^C
user@user:~/langs/c$ gcc -m32 -o 32int 3264int.c 
user@user:~/langs/c$ gcc -m64 -o 64int 3264int.c 
3264int.c: In function ‘main’:
3264int.c:4: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long unsigned int’ cat 3264int.c

我尝试将z的类型更改为int,但仍然无法编译。

2 个答案:

答案 0 :(得分:5)

这是一个警告,而不是错误。你有一个结果可执行文件。但是,如果您尝试使用-pedantic-Werror进行编译,则不会。如果您正在使用此微观示例,那么您需要做的是将格式说明符更改为%ld。在您的平台size_t上,sizeof将返回,在64位上可能是8个字节,但在32位上是4个字节。 %d可以显示32位整数,但不能显示64位整数。

答案 1 :(得分:4)

sizeof运算符返回size_t。在32位版本的平台上,这个大小与32位int相同(即,它很可能是unsigned int或long unsigned int,对于32位构建,它们都可能是32位) 。在64位版本中,它是一个长的无符号整数,它是64位。 %d用于整数,而int在32位和64位构建时均为32位。

解决这个困境的方法是:

将sizeof的结果转换为定义良好的平台无关类型 - unsigned int或更好,unsigned long,然后分别使用“%u”或“%lu”作为printf格式化字符。

或者,您可以:

使用%zu格式规范which directly supports size_t