c++clangmsys2

Gui program not using WinMain entry point


I'm trying to follow the awesome Handmade Hero series but using clang in msys2. I set up a simple program to test out the compilation however I can't get it to use the WinMain entry point.

Here's the simple program

#include <windows.h>

int main(int argc, char **argv)
{
    OutputDebugStringA(TEXT("hello console"));
    return 0;
}
    
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) 
{
    OutputDebugStringA(TEXT("hello windows"));
}

Using CodeLite the compiler/linker commands look like this:

C:/msys64/clang64/bin/clang++.exe  -c  "D:/Handmade/Handmade/main.cpp" -gdwarf-2 -fstandalone-debug -O0 -Wall   -o ../build-Debug/Handmade/main.cpp.o -IC:\msys64\clang64\include\c++\v1 -IC:\msys64\clang64\lib\clang\16\include -IC:\msys64\clang64\include  -I. -I.

C:/msys64/clang64/bin/clang++.exe -o ..\build-Debug\bin\Handmade.exe @../build-Debug/Handmade/ObjectsList.txt -L. -luser32 -Wl,-subsystem,windows

The code compiles without errors, but I see "hello console" when looking at DebugView. So WinMain is not being used as the entry point. I hoped -Wl,-subsystem,windows would make it use the gui subsystem but I guess not.

Is there a linker flag I'm missing?


Solution

  • Unlike MSVC (which picks between main() and WinMain() based on the selected subsystem), MinGW accepts both options regardless of the subsystem (regardless of -mwindows flag).

    It seems that main() has precedence over WinMain() if both are defined, and simply removing main() will make it prefer WinMain().


    If I recall correctly, MinGW provides a default main() that is a weak symbol, which calls WinMain(). So you either define WinMain() for it to call, or define main() which overrides the default.

    This also explains why MinGW says undefined reference to WinMain if neither function is defined.