Quantcast
Channel: Coding and Programing » Uncategorized
Viewing all articles
Browse latest Browse all 10

detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor

$
0
0

Problem And Question

If here’s some cross-platform C/C++ code should be compiled on Mac OS X, iOS, Linux, Windows, how can I detect them reliably during preprocessor process?

Best Solution And Answer

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:

#ifdef _WIN32
   //define something for Windows (32-bit and 64-bit, this part is common)
   #ifdef _WIN64
      //define something for Windows (64-bit only)
   #endif
#elif __APPLE__
    #include "TargetConditionals.h"
    #if TARGET_IPHONE_SIMULATOR
         // iOS Simulator
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
        // Unsupported platform
    #endif
#elif __linux
    // linux
#elif __unix // all unices not caught above
    // Unix
#elif __posix
    // POSIX
#endif

This defined macroses depends on compiler that you are going to use.

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is defined when targeting Windows, not only the x86 version. This prevents code duplication if some includes are common to both.


Viewing all articles
Browse latest Browse all 10

Trending Articles