Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between main and mainCRTStartup?

Tags:

winapi

I'm trying to understand how substituting a different entry point for WinMain works in the Microsoft toolchain.

I already found this question and it was super helpful, but one last detail is nagging at me.

The first time I changed the Linker>Advanced>Entry Point option in Visual Studio, I set it to main by mistake and my program compiled and ran fine. I realized it later and rebuilt the program with it set to mainCRTStartup, as the accepted answer in the linked question suggests, and didn't find anything different.

So, my question is: is there any difference at all between main and mainCRTStartup, and if so, what is the difference?

like image 594
Michael Avatar asked Apr 08 '14 10:04

Michael


People also ask

What is meant by WinMain?

WinMain is the conventional name used for the application entry point.

Does Windows have a main () function?

WinMain() is the C entry point function of any windows application. Like normal DOS/console based application which has main() function as C entry point, in windows we have WinMain() instead. WinMain() is a function which is called by system during creation of a process.

What is hInstance?

hInstance is something called a "handle to an instance" or "handle to a module." The operating system uses this value to identify the executable (EXE) when it is loaded in memory. The instance handle is needed for certain Windows functions—for example, to load icons or bitmaps.

How do I change the entry point in Visual Studio?

Re: setting the entry point in visual studio community 2017 Go to the Solution Explorer. Click on the project. Go to the properties line and click it. Go to the linker line.


1 Answers

main() is the entrypoint of your C or C++ program. mainCRTStartup() is the entrypoint of the C runtime library. It initializes the CRT, calls any static initializers that you wrote in your code, then calls your main() function.

Clearly it is essential that both the CRT and your own initialization is performed first. You can suffer from pretty hard to diagnose bugs if that doesn't happen. Maybe you won't, it is a crap-shoot. Something you can test by pasting this code in a small C++ program:

class Foo {
public:
    Foo() {
        std::cout << "init done" << std::endl;
    }
} TestInit;

If you change the entrypoint to "main" then you'll see that the constructor never gets called.

This is bad.

like image 189
Hans Passant Avatar answered Oct 10 '22 07:10

Hans Passant