Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinMain vs. main (C++) [duplicate]

Tags:

c++

winapi

I'm fairly new to C++, but have done some .NET programming before.

What is the difference between main(...) and WinMain(...), I wrote a program earlier with main(...) and was able to call Win32 functions just fine like I am with WinMain(...), so this leads me to ask "where would it be best to use one over the other, or does it even make a difference?"

like image 200
Jason Mills Avatar asked Sep 10 '13 01:09

Jason Mills


2 Answers

Talking about the Microsoft toolchain, conventionally, Win32 graphical applications have always started with WinMain, while main is used for console applications.

The difference between the two kinds of applications actually boils down (mostly) to a single setting in the executable, and is not in capability - a GUI application can create a console, and a console application can create a window - but in the behavior of the loader: for an exe marked as GUI the loader won't allocate any console, while a console exe will attach to the parent's console or create a new one if there isn't one.

For the entrypoint name, it is all just a matter of linker/CRT defaults: the "real" entry point of the executable is just an offset into the final executable, that points to a function that takes no parameters. It's the CRT that does its stuff, determines the parameters and then calls "your" entrypoint, so, in line of principle, they both could work exactly the same way.

The point is, the name/signature of the default entrypoint that the CRT looks for depends from the type of application you are building; if the compiler and linker are set to build a console application, they will look for a main (or wmain or _tmain, depending on Unicode settings), for a GUI application they use WinMain, and DllMain for a dll.


So:

  • use WinMain if you are building a GUI (=no console created for it at startup) application;
  • main for a console application;
  • DllMain for a dll.

Again, this all isn't written in stone (and there are ways to start a GUI application from a standard main), but "when in Rome, do as the Romans do" - i.e. it's usually best to follow the uses of the platform to avoid confusing other developers and going through untested/unsupported compiler settings just to change the signature of the entrypoint.

like image 186
Matteo Italia Avatar answered Sep 28 '22 21:09

Matteo Italia


WinMain() is Windows specific entry point to a Windows-based graphical application (you have windows stuff). main() is a standard C++ entry point (in Windows, it's a console based application)...

That said, you can use GUI stuff in console applications and allocate console in GUI applications.

I would recommend reading on consoles and GUI applications in Windows on MSDN.

like image 44
lapk Avatar answered Sep 28 '22 19:09

lapk