Why do we have Dmain?

Mike Parker aldacron at gmail.com
Fri Oct 22 07:00:25 UTC 2021


On Friday, 22 October 2021 at 05:54:21 UTC, Kirill wrote:
> I am not a compiler expert, but I genuinely would like to know 
> why we have Dmain.
>
> I've been looking at the generated assembly code recently and 
> noticed the _Dmain function. I didn't notice it before. Then 
> there is main, where Dmain is called.
>
> Why is that?

The entry point for your program is a function `_start`. That's 
implemented in the C runtime, which all D programs depend on. It 
in turn calls `main`, as it does for C and C++ programs.

The D compiler generates an `extern(C) main` function that hands 
control off to DRuntime for initialization, then in turn calling 
your application `main` (a.k.a. `_DMain`).

See:
https://github.com/dlang/druntime/blob/master/src/rt/dmain2.d#L245

If you declare your main function as `extern(C)`, then the 
compiler does not generate one and you get handed control from 
the C runtime. Which in turn means you have to handle 
initialization of the D runtime yourself.




More information about the Digitalmars-d-learn mailing list