C/C++何检查操作系统与预处理器指令

171 阅读1分钟

C/C++如何检查操作系统与预处理器指令

@TOC

C/C++开发过程中,当你的代码需要根据编译它的操作系统来做不同的事情时,应该如何做呢?

比如我想实现如下的功能:

#ifdef OSisWindows
//做一些windows特有的东西
#else 
//做unix专用的东西
#endif

操作系统预定义编译器宏

操作系统备注
Android__ANDROID__
Linux kernel__linux__
MacOSmacintosh Macintosh __APPLE__ && __MACH__
Windows_WIN32 _WIN64 __WIN32__
NUIX__unix__ __unix
Solarissun __sun
OpenBSD__OpenBSD__
FreeBSD__FreeBSD__ __FreeBSD_kernel__

代码实现

通过以下代码实现对不同操作系统的判断,进而处理不同的业务逻辑。

#ifdef _WIN64
   //检测Windows 64位平台
#elif _WIN32
   //检测Windows 32位平台
#elif __APPLE__
    #include "TargetConditionals.h"
    #if TARGET_OS_IPHONE && TARGET_OS_SIMULATOR
        // iOS模拟器
    #elif TARGET_OS_IPHONE && TARGET_OS_MACCATALYST
        // Mac Catalyst
    #elif TARGET_OS_IPHONE
        // iOS设备 
    #else
        #define TARGET_OS_OSX 1
        // macOS
    #endif
#elif __linux
    // 检测Linux平台。
#elif __unix 
    // // 检测所有未被捕获的Unix平台
#elif __posix
    // 检测POSIX兼容平台
#endif

参考文章:

Pre-defined Compiler Macros Wik

how-to-detect-reliably-mac-os-x-ios-linux-windows-in-c-preprocessor