I searched a little bit on StackOverflow and Google but couldn\'t get the idea. I want to start my application with this type of user programming:
int main()
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
.
hInstance
is one exception to the "never use global variables" rule-of-thumb. Normally no variable actually logically has scope that's module-wide. hInstance
, however, has by definition exactly module-wide scope, so actually the most logical solution is to make a global variable for it and initialize it in WinMain
.
As others have suggested, you can also use GetModuleHandle(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
.