我可以根据平台包含不同的文件吗?

Can I include different files based on platform?

我包含了一个 header 文件,它似乎只存在于 Linux 机器上,而不存在于 MacOS 机器上。虽然我可以使用 VM 来编译和 运行 代码,但如果能够在 MacOS 中执行此操作就好了。

更具体地说,我正在使用 #include <endian.h>,它在 Linux 上编译,我想对 MacOS 使用 this compatibility header,我将其包含在 [=11] 中=].我的代码按预期编译和执行,前者包含在 Linux 机器上,后者包含在 MacOS 机器上。

有没有办法在 header 中使用 platform-specific 包含(可能使用某种基于 #if 的语法)?或者这是不好的做法?

Is there a way to use platform-specific includes in the header (perhaps using some sort of #if-based syntax)?

是:

#ifdef __MACH__
... // Mac headers
#elif __unix__
... // these will work for Linux/Unix/BSD even for Mac in most cases
#elif _WIN32
... // windows 32 bit
#elif _WIN64
... // windows 64 bit
#endif

Or would this be bad practice?

我不这么认为

如果我没记错的话,另一个解决方案是在 Mac 上安装 Command Line Tool,这将使您在 Unix 中获得 gcc 的所有 headers,就像激情一样。这是对我的回答的改进,我知道我忘记了一些东西:(哦,好吧,我只用了几次 Mac 进行开发:S

  • 从 Xcode 首选项-> 下载 window 或
  • 安装命令行工具
  • 执行 xcode-select -- 从终端安装 command-line.

这里是参考:

endian.h not found on mac osx

Clang 和 GCC 支持 __has_include 预处理器条件,您可以使用它来代替测试平台定义:

#if __has_include(<endian.h>)
#include <endian.h>
#else
#include "endian.h"
#endif

不过,需要注意的一件事是,由于 <endian.h> 不是标准 header,它可能出现在另一个平台上,具有不同的定义,并没有真正帮助你.

这和我前几天写的this other answer有关