Difference between WinMain,main and DllMain in C++

2019-03-09 02:41发布

What is the difference between the three functions and when to use them??

3条回答
地球回转人心会变
2楼-- · 2019-03-09 03:37

WinMain is used for an application (ending .exe) to indicate the process is starting. It will provide command line arguments for the process and serves as the user code entry point for a process. WinMain (or a different version of main) is also a required function. The OS needs a function to call in order to start a process running.

DllMain is used for a DLL to signify a lot of different scenarios. Most notably, it will be called when

  1. The DLL is loaded into the process: DLL_PROCESS_ATTACH
  2. The DLL is unloaded from the process: DLL_PROCESS_DETACH
  3. A thread is started in the process: DLL_THREAD_ATTACH
  4. A thread is ended in the process: DLL_THREAD_DETACH

DllMain is an optional construct and has a lot of implicit contracts associated with it. For instance, you should not be calling code that will force another DLL to load. In general it's fairly difficult function to get right and should be avoided unless you have a very specific need for it.

查看更多
放荡不羁爱自由
3楼-- · 2019-03-09 03:39

main() means your program is a console application.

WinMain() means the program is a GUI application -- that is, it displays windows and dialog boxes instead of showing console.

DllMain() means the program is a DLL. A DLL cannot be run directly but is used by the above two kinds of applications.

Therefore:

  • Use WinMain when you are writing a program that is going to display windows etc.
  • Use DLLMain when you write a DLL.
  • Use main in all other cases.
查看更多
看我几分像从前
4楼-- · 2019-03-09 03:46

[Addendum to your question]

Also don't forget the DllEntryPoint:

  • When loading time is involved the entry point is DllMain.
    (Ex. COM in-process server DLL).

  • When running time is involved the entry point is DllEntryPoint.
    (Ex. LoadLibrary get called).

查看更多
登录 后发表回答