What happens when you launch a D application ?
Mike via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat May 23 04:36:14 PDT 2015
On Saturday, 23 May 2015 at 10:57:22 UTC, Suliman wrote:
>>Every D program is started as if it were a C program.
> Why is so necessary?
It's not actually necessary. You could implement the `_start`
function in your D program. Here's a D program without any C
runtime, D runtime, or main.
long __d_sys_write(long arg1, in void* arg2, long arg3)
{
ulong result;
asm
{
"syscall"
: "=a" result
: "a" 1,
"D" arg1,
"S" arg2,
"m" arg2,
"d" arg3
: "memory", "cc", "rcx", "r11";
}
return result;
}
extern(C) void __d_sys_exit(long arg1)
{
asm
{
"syscall"
:
: "a" 60,
"D" arg1,
: "memory", "cc", "rcx", "r11";
}
}
extern(C) void _start()
{
// you could put this in a main function and
// call main() from here.
auto text = "Hello, World!\n";
__d_sys_write(1, text.ptr, text.length);
__d_sys_exit(0);
}
Compile with:
gdc -fno-emit-moduleinfo -nostartfiles test.d
This produces a 733 byte "Hello World" binary.
-fno-emit-moduleinfo will prevent the compiler from generating a
lot of auxiliary code that's not needed for this program.
-nostartfiles will prevent the C runtime from being linked in.
This is a nice little experiment, but once you start trying to
use structs, classes, arrays, exceptions, or any other feature of
D, you will need more and more of the D runtime.
There may also be some things generated by GDC that get called
implicitly by the C runtime's initialization procedures (e.g.
_init, _fini, etc..) but I'm not that knowledgeable about the
compiler's codegen.
>
> What about C++ and other languages? Does they have more then
> one main?
C++ is a superset of C, so in my experience, C++ only needs C
main. However, C++ has static constructors that get called by
some of the initialization procedures in the C runtime before
actually calling main. I wonder if C++ free functions mangled in
C++...I'm not sure.
>
> Why it's more than one main is needed? Why D apps can't start
> with single main?
I don't think the current implementation is necessary. There are
probably many different ways to implement D program
initialization. I don't see why D runtime couldn't just
implement _start, omit the C runtime altogether, and do
everything in D, but I trust the compiler implementers have their
reasons.
If you're interested in digging deeper, you'll probably have to
ask questions on D.GNU to get the attention of the compiler
implementers.
Mike
More information about the Digitalmars-d-learn
mailing list