13

我正在编写一个可移植的 C++ 应用程序。如何根据其运行的操作系统包含不同的标头。有没有办法在 C++ 中做到这一点,还是我必须使用构建系统?

4

3 回答 3

11

带预处理器:

#ifdef _SUNOS
//code
#elseif _LINUX
//code
#elseif _HPUX
//code
#elseif _WIN32
//code
#else
#error OS not supported
#endif
于 2011-05-24T19:23:50.713 回答
9

我会使用预处理器指令和跨平台构建系统,例如CMake。你可以这样做:

#ifdef LINUX
#include <unistd.h>
#elif defined(WINDOWS)
#include <algorithm.h>
# elif Defined(MAC_OSX)
//... etc.
#else
#error No operating system defined
#endif

然后在构建中添加相应的预处理器标志,例如:-DLINUX.

于 2011-05-24T19:24:30.310 回答
4

我们在 Linux (Red Hat Enterprise 5)、Sun (Solaris) 和 Windows 上进行开发。我们的系统是使用这样的东西:

#ifndef MSWINDOWS
#include <unistd.h>
#else
#include <winbase.h>
#endif
//More includes here
于 2011-05-24T19:24:08.640 回答