The Question :
307 people think this question is useful
If there’s some cross-platform C/C++ code that should be compiled on Mac OS X, iOS, Linux, Windows, how can I detect them reliably during preprocessor process?
The Question Comments :
The Answer 1
526 people think this answer is useful
There are predefined macros that are used by most compilers, you can find the list here. GCC compiler predefined macros can be found here.
Here is an example for gcc:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
//define something for Windows (32-bit and 64-bit, this part is common)
//define something for Windows (64-bit only)
//define something for Windows (32-bit only)
// iOS Simulator
// iOS device
// Other kinds of Mac OS
# error "Unknown Apple platform"
#elif __unix__ // all unices not caught above
# error "Unknown compiler"
The defined macros depend on the compiler that you are going to use.
#ifdef can be nested into the
_WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both
WIN32 without underscore allows IDE to highlight the right partition of code).
The Answer 2
31 people think this answer is useful
As Jake points out,
TARGET_IPHONE_SIMULATOR is a subset of
TARGET_OS_IPHONE is a subset of
So a better approach might be:
//define something for Windows (64-bit)
//define something for Windows (32-bit)
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
// define something for simulator
// define something for iphone
#define TARGET_OS_OSX 1
// define something for OSX
#elif __unix // all unices not caught above
The Answer 3
8 people think this answer is useful
Kind of a corollary answer: the people on [this site] have taken the time to make tables of macros defined for every OS/compiler pair.
For example, you can see that
_WIN32 is NOT defined on Windows with Cygwin (POSIX), while it IS defined for compilation on Windows, Cygwin (non-POSIX), and MinGW with every available compiler (Clang, GNU, Intel, etc.).
Anyway, I found the tables quite informative and thought I’d share here.