我正在编写一个可移植的C ++应用程序。如何根据运行的操作系统包含不同的标头。有没有办法在C ++中执行此操作,还是必须使用构建系统?
答案 0 :(得分:11)
使用预处理器:
#ifdef _SUNOS
//code
#elseif _LINUX
//code
#elseif _HPUX
//code
#elseif _WIN32
//code
#else
#error OS not supported
#endif
答案 1 :(得分:8)
我会使用预处理程序指令和跨平台构建系统,例如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
。
答案 2 :(得分:4)
我们在Linux(Red Hat Enterprise 5),Sun(Solaris)和Windows上开发。我们的系统是使用这样的东西:
#ifndef MSWINDOWS
#include <unistd.h>
#else
#include <winbase.h>
#endif
//More includes here