How can I write a Windows application without using WinMain?

Matthew Murdoch picture Matthew Murdoch · Feb 19, 2009 · Viewed 10.7k times · Source

Windows GUI applications written in C/C++ have 'WinMain' as an entry point (rather than 'main'). My understanding of this is that the compiler generates a 'main' function to be called by the C Runtime. This 'main' function sets up the necessary environment for the GUI and calls into 'WinMain' (specifying the instance handles etc.).

In short, I believe console and GUI application startup to differ in the following way:

Console application: C Runtime --> 'main' function (hand-coded)

GUI application: C Runtime --> 'main' function (compiler-generated) --> 'WinMain' function (hand-coded)

I would like to both validate this understanding and find out how I can hand-code a Windows GUI with just a 'main' function (i.e. without having to write 'WinMain').

Answer

Erik Funkenbusch picture Erik Funkenbusch · Feb 19, 2009

You have an incorrect understanding. The difference between main and WinMain, apart from some differet initialization code, is the parameters passed to it.

main looks like this:

int main(int argc, char* argv[]);

While WinMain looks like this:

int WINAPI WinMain(HINSTANCE hInstance,
    HINSTANCE hPrevInstance,
    LPSTR lpCmdLine,
    int nCmdShow
);

Something has to setup those parameters and make the call, and that's the startup code. When you compile and link a program, one of the linker parameters is the entry point, and that will be, depending on a console or GUI app, a different bit of startup code.

You can certainly write your own startup code, just go into your visual c++ source directory and you can find the startup code, it's called crt0.c and it's in the VC\crt\src directory.