Macos – How to force 64 bit integer arithmetic on OS X

c++gccmacosmath

I am trying to force 64 bit long integers on OS X 10.5.6. running on an Apple MacBook Intel Core 2 Duo. Here is my c code:

#include<stdio.h>

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);
}

Compiling without any switches yields the following:

$ gcc testlong.c -o testlong ;./testlong

a== 2147483647. sizeof(a) == 4  
aplus1 = -2147483648 

Compiling with the -m64 switch yields:

$ gcc testlong.c -o testlong -m64; ./testlong

a== 2147483647. sizeof(a) == 8  
aplus1 = -2147483648 

So the second version is apparently using 64 bit storage, but still generates the overflow error, although 2^32 should be well within the range of a 64 bit integer. Any ideas?

I would prefer a solution that can be forced from a gcc option rather than requiring me to change multiple lines of source code (my actual problem is not the above example specifically, rather I need to force long integer arithmetic in a more general situation).

Best Solution

Not only do you have to use long long, but you must also change the printf() statements accordingly.

#include<stdio.h>

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 is the code for long longs.

Apparently true 64-bit programs can use %d for 64-bit integers - I don't know if it's possible to configure it to compile in this mode.