确定在C ++中是Linux还是Windows

我正在用C ++编写一个跨平台兼容的函数,根据input文件名创build目录。 我需要知道该机器是Linux还是Windows,并使用适当的正斜杠或反斜杠。 对于下面的代码,如果机器是Linux,那么isLinux = true 。 我如何确定操作系统?

 bool isLinux; std::string slash; std::string directoryName; if isLinux slash = "/"; else slash = "\\"; end boost::filesystem::create_directory (full_path.native_directory_string() + slash + directoryName); 

使用:

 #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) static const std::string slash="\\"; #else static const std::string slash="/"; #endif 

顺便说一句,你仍然可以安全地在Windows上使用这个斜杠“/”,因为Windows完全理解这一点。 所以只要坚持用“/”斜杠就可以解决所有操作系统的问题,就像OpenVMS的路径是foo:[bar.bee]test.ext可以表示为/foo/bar/bee/test.ext

一般来说,你有这样做有条件的编译。

也就是说,如果你使用boost::filesystem你应该使用可移植的通用路径格式,这样你就可以忘记这样的事情。

默认情况下,Visual Studio#在预处理器项目设置中定义_WIN32

所以你可以使用

 // _WIN32 = we're in windows #ifdef _WIN32 // Windows #else // Not windows #endif 

看看http://en.wikipedia.org/wiki/Uname

如果您使用g ++作为您的编译器/ GNU,那么您可以尝试下面的代码。 符合POSIX的环境支持:

 #include <stdio.h> #include <sys/utsname.h> #include <stdlib.h> int main() { struct utsname sysinfo; if(uname(&sysinfo)) exit(9); printf("os name: %s\n", sysinfo.sysname); return 0; } 

最常用的方法之一是使用预处理器指令 。 链接是用于C但在C ++中使用相同的方式。 公平的警告,每个编译器和操作系统可以有自己的一套指令。

predef.sourceforge.net是一个综合的各种MACRO,用于识别编译器/操作系统等等。 (直接链接到操作系统子站点)