Home >Backend Development >C++ >How Can I Reliably Detect the Operating System During C Preprocessor Compilation?

How Can I Reliably Detect the Operating System During C Preprocessor Compilation?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-15 07:10:14261browse

How Can I Reliably Detect the Operating System During C Preprocessor Compilation?

Preprocessor Detection of Operating Systems in C

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

elif APPLE

#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

elif ANDROID

// Handled elsewhere (Android typically conforms to __linux__)

elif linux

// Linux

elif unix

// Unix

elif defined(_POSIX_VERSION)

// POSIX

else

// Error: Unknown compiler

endif

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn