Home >Backend Development >C++ >How Can I Reliably Detect the Operating System During C Preprocessor Compilation?
Detecting the operating system during preprocessor processing is essential for writing cross-platform C/C code. Here's how to achieve this reliably for Mac OS X, iOS, Linux, and Windows:
Most compilers define macros that identify the operating system. For preprocessor detection, these predefined macros are crucial. GCC, for instance, has a comprehensive list, which includes:
</p> <h1>if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)</h1> <pre class="brush:php;toolbar:false">// Define something for Windows (32-bit and 64-bit) #ifdef _WIN64 // Define something unique for Windows (64-bit only) #else // Define something specific for Windows (32-bit only) #endif
#include <TargetConditionals.h> #if TARGET_IPHONE_SIMULATOR // iOS, tvOS, or watchOS Simulator #elif TARGET_OS_MACCATALYST // Mac's Catalyst (bridging iOS API into Mac) #elif TARGET_OS_IPHONE // iOS, tvOS, or watchOS device #elif TARGET_OS_MAC // Other Apple platforms #else // Error: Unknown Apple platform #endif
// Handled elsewhere (Android typically conforms to __linux__)
// Linux
// Unix
// POSIX
// Error: Unknown compiler
By using these macros, you can reliably detect the operating system during preprocessor processing and tailor your code accordingly, ensuring compatibility across various platforms.
The above is the detailed content of How Can I Reliably Detect the Operating System During C Preprocessor Compilation?. For more information, please follow other related articles on the PHP Chinese website!