在 C++ 中检测 Windows 操作系统

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4363547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 15:44:18  来源:igfitidea点击:

Detect if windows operating system in C++

c++windows

提问by Daniel

How can i detect if the operating system is Windows in C++/C?

如何在 C++/C 中检测操作系统是否为 Windows?

Thanks

谢谢

回答by Paul

#ifdef _WIN32
cout << "This is Windows." << endl;
#endif

This will allow you define blocks for windows only. As long as the preprocessor macro is defined.

这将允许您仅为窗口定义块。只要定义了预处理器宏。

This is a compile time thing, not a runtime thing.

这是编译时的事情,而不是运行时的事情。

回答by Jeremy Edwards

You can use getenv()from cstdliblike so:

您可以像这样getenv()cstdlib使用:

#include <cstdlib>

getenv("windir");

If you get NULLthen it's not windows.

如果你得到NULL那么它不是窗户。

This works since %windir%should only be defined on windows systems. This is a cheap and dirty hack of course.

这是有效的,因为%windir%应该只在 Windows 系统上定义。这当然是一个廉价而肮脏的黑客。

http://www.cplusplus.com/reference/clibrary/cstdlib/getenv/

http://www.cplusplus.com/reference/clibrary/cstdlib/getenv/

回答by Ruel

If it's runtime, you might be referring to Wine (on non-windows operating systems). If not, that's just plainly impossible. Windows binaries cannot run in other operating systems (except if they have Wine).

如果是运行时,您可能指的是 Wine(在非 Windows 操作系统上)。如果没有,那显然是不可能的。Windows 二进制文件不能在其他操作系统中运行(除非它们有 Wine)。

If it's compile time, possible duplicate: Are there any macros to determine if my code is being compiled to Windows?

如果是编译时间,则可能重复:是否有任何宏可以确定我的代码是否正在编译到 Windows?

(see accepted answer above)

(见上面接受的答案)