windows C++中WinMain、main和DllMain的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/416739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between WinMain,main and DllMain in C++
提问by Ahmed Said
What is the difference between the three functions and when to use them??
这三个函数有什么区别,什么时候用??
采纳答案by JaredPar
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 starta process running.
WinMain 用于应用程序(以 .exe 结尾)以指示进程正在启动。它将为进程提供命令行参数,并作为进程的用户代码入口点。WinMain(或不同版本的 main)也是一个必需的函数。操作系统需要调用一个函数来启动进程运行。
DllMain is used for a DLL to signify a lot of different scenarios. Most notably, it will be called when
DllMain 用于 DLL 以表示许多不同的场景。最值得注意的是,它会在什么时候被调用
- The DLL is loaded into the process: DLL_PROCESS_ATTACH
- The DLL is unloaded from the process: DLL_PROCESS_DETACH
- A thread is started in the process: DLL_THREAD_ATTACH
- A thread is ended in the process: DLL_THREAD_DETACH
- DLL 加载到进程中:DLL_PROCESS_ATTACH
- DLL 从进程中卸载:DLL_PROCESS_DETACH
- 进程中启动了一个线程:DLL_THREAD_ATTACH
- 一个线程在进程中结束: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.
DllMain 是一个可选的构造并且有很多与之相关的隐式契约。例如,您不应该调用会强制加载另一个 DLL 的代码。一般来说,要正确使用它是相当困难的,除非您有非常特殊的需求,否则应该避免使用它。
回答by Frederick The Fool
main()means your program is a console application.
main()表示你的程序是一个控制台应用程序。
WinMain()means the program is a GUI application-- that is, it displays windows and dialog boxes instead of showing console.
WinMain()表示该程序是一个GUI 应用程序——也就是说,它显示窗口和对话框而不是显示控制台。
DllMain()means the program is a DLL. A DLL cannot be run directly but is used by the above two kinds of applications.
DllMain()表示程序是一个DLL。DLL 不能直接运行,而是被上述两种应用程序使用。
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.
- 当您编写要显示窗口等的程序时,请使用 WinMain。
- 编写 DLL 时使用 DLLMain。
- 在所有其他情况下使用 main。
回答by Migrate2Lazarus see my profile
[Addendum to your question]
[对你的问题的补充]
Also don't forget the DllEntryPoint:
也不要忘记 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).
当涉及加载时间时,入口点是 DllMain。
(例如,COM 进程内服务器 DLL)。当涉及运行时间时,入口点是 DllEntryPoint。
(例如 LoadLibrary 被调用)。