C++ 编译时宏来检测 Windows 操作系统
是否存在任何 C++ 编译时宏来检测代码正在哪个 Windows 操作系统上编译.我基本上只想在Win7上支持某些功能.所以我有兴趣做这样的事情
Are there any C++ compile time macros which exists to detect which Windows OS the code is being compiled on. I basically want to support certain functions only on Win7. So I am interested in doing something like this
#if <os_macro> = WIN7
// This function would do something valid only on Win7 builds.
bool myfunction {
// do something here
}
#else
// This function would typically return false, since its not supported on OS below win7
bool myfunction {
return false;
}
#endif
还有其他更好的方法吗?
Is there any other better way to do this?
推荐答案
编译的操作系统并不是那么重要;更重要的是代码 运行 的操作系统,您显然无法在编译时检测到.但是如果你想让你的代码在旧版本的 Windows 上运行,你可以设置 WINVER
和 _WIN32_WINNT
到某些值,这将导致更新的功能不可用等(只需搜索 Windows 标题测试这些宏以获得想法的文件).
The OS that it's getting compiled on is not all that important; what matters more is the OS that the code is running on, which you obviously cannot detect at compile time. But if you want your code to run on older versions of Windows, you can set WINVER
and _WIN32_WINNT
to certain values, which will cause newer functions not to be available etc. (just search the Windows header files for where those macros get tested to get an idea).
要在运行时测试功能,请使用 GetProcAddress
(也可能还有 LoadLibrary
,如果它在较新的 DLL 中)来测试函数是否可用.如果是,就调用它,如果不是,不要.
To test for functionality at runtime, use GetProcAddress
(and possibly also LoadLibrary
, if it's in a newer DLL) to test if the function is available. If it is, call it, if not, don't.
另请参阅 Visual Studio 编译器使用的 预定义宏,如果你想检测编译器版本等.
See also the predefined macros used by the Visual Studio compiler if you want to detect the compiler version etc.
相关文章