如何在 C 预处理器中可靠地检测 Mac OS X、iOS、Linux、Windows?

时间:2022-10-16
本文介绍了如何在 C 预处理器中可靠地检测 Mac OS X、iOS、Linux、Windows?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

如果有一些跨平台的 C/C++ 代码应该在 Mac OS X、iOS、Linux、Windows 上编译,我如何在预处理过程中可靠地检测它们?

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

推荐答案

有大多数编译器使用的预定义宏,你可以找到列表 此处.GCC 编译器预定义宏可以在此处找到.以下是 gcc 的示例:

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:

#if defined(WIN32) || defined(_WIN32) || defined(__WIN32__) || defined(__NT__)
   //define something for Windows (32-bit and 64-bit, this part is common)
   #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 Simulator
    #if TARGET_OS_MACCATALYST
         // Mac's Catalyst (ports iOS API into Mac, like UIKit).
    #elif TARGET_OS_IPHONE
        // iOS device
    #elif TARGET_OS_MAC
        // Other kinds of Mac OS
    #else
    #   error "Unknown Apple platform"
    #endif
#elif __linux__
    // linux
#elif __unix__ // all unices not caught above
    // Unix
#elif defined(_POSIX_VERSION)
    // POSIX
#else
#   error "Unknown compiler"
#endif

定义的宏取决于您要使用的编译器.

The defined macros depend on the compiler that you are going to use.

_WIN64 #ifdef 可以嵌套到_WIN32 #ifdef 因为_WIN32code> 甚至在面向 Windows x64 版本时定义.如果某些标头包含对两者通用,则这可以防止代码重复(也WIN32 没有下划线允许IDE 突出显示代码的正确分区).

The _WIN64 #ifdef can be nested into the _WIN32 #ifdef because _WIN32 is even defined when targeting the Windows x64 version. This prevents code duplication if some header includes are common to both (also WIN32 without underscore allows IDE to highlight the right partition of code).

这篇关于如何在 C 预处理器中可靠地检测 Mac OS X、iOS、Linux、Windows?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:计算 pow(a,b) mod n 下一条:静态库和共享库的区别?

相关文章

最新文章