Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

winapi - What is the difference between main and mainCRTStartup?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...