Abandoned Wig
Hi, I'm Martin.
I work on the Web Platform at Igalia.

Compiling D Source is Easy

18 January 2009
There are two compilers available for D. The original D compiler (the one written by Walter) is DMD. It has an open-source front-end (the part that generate the IL) and a proprietary, closed-source back-end (the part that converts the IL into machine code). Two other, fully open-source compilers exist, GDC and LDC, which use the GCC and LLVM back-ends respectively.

I like using GDC, because it's open-source and has better support for shared library linking on Unices. It's fairly easy to switch between GDC and DMD, as GDC includes a gdmd command which emulates the command-line behavior of DMD.

Previously I was using DSSS to build my D projects. While DSSS is very nice in many ways, it felt odd using a build tool that was really only popular in the D community. After we started using SCons at work, I was positively pickled to find that it supported building D code. SCons works just as easily for D code as it does for building other things.

Say you have a source file containing your ground-breaking implementation of the Smash Mouth Optimization (see Computational Football vol. 23), SmashMouth.d. To build this with SCons, simply create a SConstruct file that looks like this:
BuildDir('build', 'src')
e = Environment()
e.Program('build/SmashMouth.d')
This assumes that you have your source in a folder called src and you want to build into a folder called build (I know, I know...this is a pretty brazen assumption). Running scons should produce something like this:
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
gcc -o build/Test build/Test.o -lgphobos -lpthread -lm -lgphobos -lgphobos -lgphobos
scons: done building targets.
You can see here that scons decided to build using GDC and Phobos. The SCons D scanner is pretty smart about what compilers you have on your system. It's also configurable. Okay, here comes the magical wonderland part.

What happens when you decide that you want SmashMouthOptimizer to be a shared library? You have some options here.

  • You could simply look through all the man pages of the D compilers you are using, hunt for all the relevant linking options, and finally write conditional code in your Makefile to use them.

  • On the other hand, you could just change your SConstruct to look like this:
    BuildDir('build', 'src')
    e = Environment()
    e.SharedLibrary('build/SmashMouth.d')
    Then let scons do this:
    scons: Reading SConscript files ...
    scons: done reading SConscript files.
    scons: Building targets ...
    gdmd -I. -c -ofbuild/SmashMouth.os build/SmashMouth.d
    gcc -o build/libSmashMouth.so -shared build/SmashMouth.os
    scons: done building targets.