Replacing WinMain() with main() function in Win32 programs

You can use standard main in a "windows" app (that is, a GUI subsystem Windows application) even with the Microsoft tools, if you add the following to the Microsoft linker options:

/subsystem:windows /ENTRY:mainCRTStartup

Note that this is not necessary for the GNU toolchain.

Still for the Microsoft tools you can alternatively add this to your main file:

#ifdef _MSC_VER
#    pragma comment(linker, "/subsystem:windows /ENTRY:mainCRTStartup")
#endif

James McNellis tells you how to get the hInstance.


GetModuleHandle(NULL) will give you hInstance. hPrevInstance is always NULL.


First, GetModuleHandle(0) provides the executable's module handle, which is the same as the hInstance argument of WinMain.

With the GNU toolchaing (g++ compiler), the standard-conforming code is OK.

The Microsoft toolchain, however, only accepts the standard-conforming code by default for a console subsystem executable. To create a GUI subsystem executable with this non-conforming toolchain, using a standard main, you have to specify a Microsoft runtime library entry point that calls the standard main, namely mainCRTStartup. For a command line invocation that means…

cl myApp.cpp /link /entry:mainCRTStartup /subsystem:windows user32.lib

As a practical matter, for working in the command line you can simply specify the entry point in the LINK environment variable:

set LINK=/entry:mainCRTStartup

cl myApp.cpp /link /subsystem:windows user32.lib

Creating a similar standard-conforming setup for Visual Studio is perhaps not desirable, since some Visual Studio project types (mainly MFC) requires use of Microsoft's non-standard WinMain or wWinMain.

Tags:

C++

Winapi