c++winapimingwmingw32winmain

Undefined reference to WinMain when trying to use wWinMain (C++ MinGW)


Currently, I am trying to make a Windows application using C++. For compiling my program I use MinGW (GCC). But as soon as I use int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow) instead of int main() the compiler shows me the following message:

C:/mingw-w64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/8.1.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x2e): undefined reference to `WinMain'
 collect2.exe: error: ld returned 1 exit status
The terminal process terminated with exit code: 1

The example code I tried to compile I got from this Windows application tutorial:

Example Code

I have already tried reinstalling MinGW but it did not help (also I'm using Windows 10).


Solution

  • Newer Mingw versions support -municode linker option switching to alternate startup code allowing to use wWinMain instead of WinMain (or wmain instead of main). Add it to your command line, linker options in IDE or makefile.

    g++ other_options_and_arguments -municode
    

    Older versions do not support this option.

    One thing to note is that Visual C++ supports a “wWinMain” entry point where the “lpCmdLine” parameter is a “LPWSTR”. You would typically use the “_tWinMain” preprocessor definition for your entry point and declare “LPTSTR lpCmdLine” so that you can easily support both ANSI and Unicode builds. However, the MinGW CRT startup library does not support wWinMain, so you’ll have to stick with the standard “WinMain” and use “GetCommandLine()” if you need to access command line arguments.

    via Building Win32 GUI Applications with MinGW

    In this specific case, you can use WinMain instead. This program doesn't use pCmdLine value, so it should compile when you change wWinMain to WinMain and PWSTR pCmdLine to PSTR pCmdLine.

    If you later would need unicode command line use LPWSTR cmd_line = GetCommandLineW(); instead of WinMain argument.