Detecting Operating Systems in the C Preprocessor for Cross-Platform Development
Determining the underlying operating system during the preprocessor stage is crucial for cross-platform C/C code. Fortunately, most compilers define specific macros that allow for reliable detection.
GCC and Clang Macros
GCC and Clang compilers provide a comprehensive list of predefined macros that can be used for OS identification:
Example for GCC
Here's an example of how these macros can be utilized in a GCC compilation:
#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__) // Define something for Windows (32-bit and 64-bit) #ifdef _WIN64 // Define something for Windows (64-bit only) #else // Define something for Windows (32-bit only) #endif #elif __APPLE__ #include <TargetConditionals.h> #if TARGET_IPHONE_SIMULATOR // iOS, tvOS, or watchOS Simulator #elif TARGET_OS_MACCATALYST // Mac's Catalyst (ports iOS API into Mac, like UIKit). #elif TARGET_OS_IPHONE // iOS, tvOS, or watchOS device #elif TARGET_OS_MAC // Other kinds of Apple platforms #else #error "Unknown Apple platform" #endif #else #error "Unknown compiler" #endif
Important Considerations
The above is the detailed content of How Can I Detect the Operating System in the C Preprocessor for Cross-Platform Development?. For more information, please follow other related articles on the PHP Chinese website!