What happens when you launch a D application ?

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri May 22 07:49:52 PDT 2015


On 5/22/15 2:36 AM, Suliman wrote:
> On SO[1] I got next answer:
>
> "What happens when you launch a D application ? The entry point is a C
> main inside the runtime, which initialize it (the runtime), including
> module constructor, run the unittest (if you've compiled with
> -unittest), then call your main (which name is "_Dmain" - useful to know
> if you want to set a breakpoint with GDB). When Vibe.d's main is called,
> it parses command line argument, an optional config file, and finally,
> starts the event loop. Any code that wish to run once the event loop has
> started should use runTask and similar, or createTimer. They should not
> call the code directly from the static constructor (it's actually one of
> the most common mistake when starting with Vibe.d)."
>
> Could you explain what mean "C main inside the runtime". I thought that
> is only one main is possible. And why it's named "*ะก* main" D is not
> C-translated language.
>
> Same question is about _Dmain -- what is it?
>
> If I will call this() before main? What it will be? Will it run before
> main?

Druntime defines the main function that C runtime will call. C runtime 
intializes its own things (e.g. stdin/stdout/stderr) and then calls C main.

Druntime's version of C main then intializes all things that D needs 
(and there's quite a bit) not in any specific order:

- set up the main thread
- initialize the GC
- detect module constructor/destructor cycles
- run module constructors (both shared and thread-local)
- run unittests if enabled
- run your main function (defined in D as 'main')

After main exits, it unwinds all this stuff.

FYI, I didn't realize this (but just figured it out), C main *used* to 
be in druntime, but it's now generated by the compiler. See here:

https://github.com/D-Programming-Language/dmd/blob/master/src/mars.c#L236

The function it calls (_d_run_main) is now the entry point into 
druntime, and it is here:

https://github.com/D-Programming-Language/druntime/blob/master/src/rt/dmain2.d#L290

It can give you more clues as to how it works.

-Steve


More information about the Digitalmars-d-learn mailing list