tags:

views:

252

answers:

4

I have a C++ app that uses wxWidgets. Certain parts of the app differ for 32 and 64 bit hosts. Currently I use sizeof(void *), but is there a better way that uses conditional compilation and is platform neutral?

+3  A: 

Typically people use #defines to determine bitness (the exact define will depend on the compiler). This is better than a runtime approach using sizeof(void*).

As for platform neutral, well, some compilers are on multiple platforms..

Terry Mahaffey
What would that look like for gcc/Mingw32?
George Edison
http://stackoverflow.com/questions/682934/is-there-a-gcc-preprocessor-directive-to-check-if-the-code-is-being-compiled-on-a
Terry Mahaffey
+2  A: 

Depending on your compiler you may have access to platform specific macros. Try to look up their documentation.

dirkgently
+1  A: 

All common compilers have predefined preprocessor macros that identify the platform. For example, if you are using GCC, you can check them all easily:

touch foo.h; g++ -E -dM foo.h

which yields among others

#define linux 1
#define __x86_64 1

for me, since I'm using a 64b linux at the moment, and

#define __APPLE__ 1
#define __i386 1

on a 32b OS X, I hear.

For Sun Studio 12, they are documented here. Also, Sun Microsystems considers them as part of the API of the compiler so compatibility is ensured. For example, on my Solaris box, I have __SunOS_5_10 and __sparcv9 defined (implies 64b).

On AIX systems with the IBM xlc compiler, take a look at /etc/vac.cfg and its options keyword fields to find out the predefined macros. There are at least _AIX and more specific _AIX61 as well as _POWER (on a 64b PPC) defined on a system where I have access.

On HP-UX and its aCC compiler, there's at least the __ia64 macro on itanium. Some other aCC specific predefined macros are documented here.

okun
A: 

What's wrong with using sizeof() where the size matters? The compiler will happily optimise it away to a constant.

Autopulated
But then what if the if-block uses architecture specific functions?
George Edison
Surely they are platform specific, rather than architecture specific? in which case you can use the preprocessor macros.If there really are architecture specific functions on the same platform(!) then you could use #if defined(), I suppose. That sounds very strange though.
Autopulated
No. For example, Microsoft's Text-to-Speech API is initialized two different ways for 32 bit and 64 bit mode.
George Edison
Microsoft are a responsible for a lot of quality code, but unless there is a very good reason that sounds like the most mind-numbingly dumb design decision ever.
Autopulated
I know :) I better fix my code I guess.
George Edison