Last active
August 29, 2015 14:28
-
-
Save paulbuis/500e5acb3ce1bc6b9b6a to your computer and use it in GitHub Desktop.
D version of 2 source file hello world example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
void hello(int repeatCount) nothrow { | |
try { | |
foreach (i; 0..repeatCount) { | |
printf("hello from D\n"); | |
} | |
} | |
catch (Throwable t) { | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hello; | |
void main() { | |
hello.hello(3); | |
} |
When compiled and linked using the GNU D compiler under Linux, the executable is large since it is statically linked with the entire D runtime library. The runtime library is separate from the Phobos standard library that defines the API for functions & types intended to be invoked by D after the appropriate import statements are included in the D source. The LVM compiler/linker appears to support shared library linkage to the D library, resulting in a smaller executable, but not necessarily smaller RAM requirements.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Putting code in file named hello.d creates a module named hello. Putting a function with the same name there makes the function's full name hello.hello(). Unlike with C, one does not need a separate header file to hold the function prototypes. However, hello.d must be compiled before main.d and the compiler will extract the type information out of the compilation results. The type information includes not only the return type and argument type, but also the detail that this is a "nothrow" function which, in principle, would make it easier to call from C which doesn't have any exception handling. Like with C++, the hello() function name will be mangled to encode this information unless it is declared with as "extern (C)" which in addition to possibly changing how arguments are passed, also turns off name mangling (as is, nm reports the function name as "_D5hello5helloFNbiZv" ).
Note that D inferred the type of i to be compatible with the values in the range 0..3.