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?
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..
Depending on your compiler you may have access to platform specific macros. Try to look up their documentation.
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.
What's wrong with using sizeof()
where the size matters? The compiler will happily optimise it away to a constant.