使用#if运行函数



我试图运行表达式_setmode只有当我使用Windows,和setlocale只有当我使用Linux,但我不能设法使他们工作与一个简单的if-else内一个函数由于Linux有错误与Windows库,反之亦然。

#if defined(_WIN32) || defined(_WIN64) || (defined(__CYGWIN__) && !defined(_WIN32))
#define PLATFORM_NAME 0
#include <io.h>
#include <fcntl.h>
#elif defined(__linux__)
#define PLATFORM_NAME 1
#include <locale>
#elif defined(__APPLE__) && defined(__MACH__)
#include <TargetConditionals.h>
#if TARGET_OS_MAC == 1
#define PLATFORM_NAME 2
#endif
#else
#define PLATFORM_NAME NULL
#endif
#if PLATFORM_NAME == 0
_setmode(_fileno(stdout), _O_U8TEXT);
#endif
#if PLATFORM_NAME == 1
setlocale(LC_CTYPE, "");
#endif

如果您编写依赖于操作系统的*代码(如本例),您可以在编译时**管理它。为此,我们需要两个部分:

  1. 定义操作系统相关常量(可选,如果条件简单,这部分可以省略):
#if defined(_WIN32)
#define PLATFORM_NAME 0
#include <fcntl.h>
#include <io.h>
#elif defined(__linux__)
#define PLATFORM_NAME 1
#include <locale>
#endif
  1. 在需要的地方调用具有预处理器条件的操作系统相关代码:
#if PLATFORM_NAME == 0
//Windows code here
#endif

你可以写更复杂的条件:

#if PLATFORM_NAME == 0
//Windows code here
#elif PLATFORM_NAME != 0
//Non-Windows code here
#if PLATFORM_NAME == 1 || PLATFORM_NAME == 2
//Linux or unknown OS code here
#endif
#endif

查看此处的条件限制

提示:如果你的代码有入口点(例如main函数),你可以在main中调用大多数操作系统相关的代码,如果这有助于减少代码。在库中,您可以将依赖于操作系统的代码放置到专用的源文件函数中,例如这里。使用预处理器时间代码是编写零成本运行时代码的好方法,因为预处理器会删除所有不满足条件的源代码。

* -或任何依赖😃

** -更准确地说,预处理器时间

来源:GNU, Microsoft docs.

最新更新