繁体   English   中英

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

[英]Why can I compile this in 32bit but not 64 bit?

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,但仍然无法编译。

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

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格式规范, 它直接支持size_t

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM