tags:

views:

1836

answers:

3

I am trying to do something like the following;

#ifdef 64-bit
    #define DECIMAL_FORMAT %ld
#else
    #define DECIMAL_FORMAT %d
#endif
.
intptr_t d;  
.
printf(“Some message with DECIMAL_FORMAT in the middle of it\n”, d);

The variable 'd' being of the type 'intptr_t' needs '%d' format specifier on 32 bit machines and format specifier '%ld' on 64 bit machines. I am looking a solution to be able to compile the code on both 32 bit machines and 64 bit machines without making changes to the GCC command line or the source code.

+10  A: 

I think __LP64__ might be what you're looking for. See http://gcc.gnu.org/onlinedocs/gcc-4.1.2/cpp/Common-Predefined-Macros.html

Maybe a better way to go, though, is to use the %p specifier to printf() instead of %ld or %d. Then you don't even have to worry what your pointer size is.

Fred Larson
+1  A: 

A recommended solution is to make your application behave more predictably. If you make it dependent on the size of a memory pointer, you may have some undesirable surprises. Printf only understands a few types, if you must print a value for a type that you can't always ensure that it is really known, it is much better to convert it to something known.

printf("Some message with %ld in the middle of it\n", (long) d);

This is a good advice, and valid for any type. For example, to print a Unix PID (that is of type pid_t):

pid_t pid = fork();
printf("Fork returned %d.\n", (int) pid);

You don't have to know what is the type and size of pid, as long as the target type is large enough.

Juliano
I agree with your general philosophy, but note that you shouldn't depend on pointers fitting into a long. On 64-bit Windows, they don't (http://msdn.microsoft.com/en-us/library/s3f49ktz(VS.71).aspx). For pointers, "%p" is the right way (as Fred Larsen pointed out).
Mr Fooz
+2  A: 

You want to use the PRI* macros defined in inttypes.h. You enable them by defining __STDC_FORMAT_MACROS. You can then use

 intptr_t d = ... ;
 printf("This is an intptr_t: " PRIxPTR "\n", d);

The PRIxPTR macro will expand to %llx if __WORDSIZE == 64, and %lx otherwise.

JesperE
+1 really cool. However, the results on my x86-64 Debian system are slightly different. "echo __WORDSIZE | g++ -xc++ -include limits.h -P -E -" returns 64. "echo PRIxPTR | g++ -xc++ -D__STDC_FORMAT_MACROS -include inttypes.h -E - | tail -1" returns "l" "x".
sigjuice
Well, the PRI*-macros are c99, so if you can demonstrate that they are misbehaving on your machine your should probably report a bug to the debian people.
JesperE