C++ compile time macros to detect windows os

旧巷老猫 提交于 2019-11-28 12:28:44

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).

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.

See also the predefined macros used by the Visual Studio compiler if you want to detect the compiler version etc.

There are a set of standard windows header macros to tell you the exact version of the OS

At least with MS VC++, WIN32, _WIN32, and _WIN32_WINNT, for starters. Unless you need to control it at compile time, you might consider using something like GetVersionEx to detect at run-time, so the same build runs on older versions, but takes advantage of new features when they're available.

My two cents for people that want to compile / include differently between CONSOLE and WIN32 App under visual Studio (2017) in my case.

You you use wizard to create a Console App, You will have:

WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)

under:

If You use wizard for win32 GUI App:

WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions) so NO _CONSOLE.

so You can write:

#ifdef _CONSOLE
// for Console
#else
// for GUI


#endif // _CONSOLE



int main()
{
#ifdef _CONSOLE
    // for Console
#else
    // for GUI


#endif // _CONSOLE


    return 0;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!