如何在OS X上强制使用64位整数运算?

我试图在OS X 10.5.6上强制64位长整数。 在Apple MacBook Intel Core 2 Duo上运行。 这是我的c代码:

#include int main() { long a = 2147483647; /*== 2^32 - 1*/ long aplus1; printf("a== %d. sizeof(a) == %d \n", a, sizeof(a)); aplus1 = a+1; printf("aplus1 = %d \n", aplus1); } 

没有任何开关进行编译会产生以下结果:

 $ gcc testlong.c -o testlong ;./testlong a== 2147483647. sizeof(a) == 4 aplus1 = -2147483648 

使用-m64开关进行编译可以得到:

 $ gcc testlong.c -o testlong -m64; ./testlong a== 2147483647. sizeof(a) == 8 aplus1 = -2147483648 

所以第二个版本显然是使用64位存储,但仍然会产生溢出错误,尽管2 ^ 32应该在64位整数的范围内。 有任何想法吗?

我更喜欢可以从gcc选项中强制使用的解决方案而不是要求我更改多行源代码(我的实际问题不是上面的例子,而是我需要在更一般的情况下强制执行长整数运算)。

您不仅需要使用long long,还必须相应地更改printf()语句。

 #include int main() { long long a = 2147483647; /*== 2^32 - 1*/ long long aplus1; printf("a== %lld. sizeof(a) == %d \n", a, sizeof(a)); aplus1 = a+1; printf("aplus1 = %lld \n", aplus1); } 

%lld是long longs的代码。

显然,真正的64位程序可以将%d用于64位整数 – 我不知道是否可以将其配置为在此模式下编译。

如果您使用的是C99,请包含stdint.h并使用uint64_tint64_t 。 除此之外, unsigned long long a = 0x100000000ull; 也应该工作。

使用C99标准:

 #include  uint64_t a = 2147483647ULL; 

在Dinkumware上有一个出色的C99库概述 。

你有没有尝试过:

 long long a = 2147483647; 

C代码中的文字2147483647的类型为int 。 如果你想要它很long ,那么在左侧有一个long没有帮助,它仍然是右边的一个int

通过附加’L’: 2147483647L (建议使用大写,小写’l’也可以,但根据字体可能会非常混乱),使其成为长文字。