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

后端 未结 4 1564
無奈伤痛
無奈伤痛 2020-11-28 04:56

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


        
相关标签:
4条回答
  • 2020-11-28 05:32

    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.

    0 讨论(0)
  • 2020-11-28 05:32

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

    0 讨论(0)
  • 2020-11-28 05:35

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

    0 讨论(0)
  • 2020-11-28 05:45

    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.

    0 讨论(0)
提交回复
热议问题