Sunday, March 15, 2009

D Conditional Compilation

The D programming language supports conditional compilation using version identifiers and version numbers, a solution that is slightly better than the #ifdef, pre-processor driven, way of C/C++ that most of us are used to.

When using the .NET compiler for D that I am developing, one will be able to import and take advantage of .NET assemblies. For example the System.Console.WriteLine family of functions may come in handy. But such code would not compile when fed to the native Digital Mars D compiler.

Conditional compilation and the version identifier D_NET do the trick, like in this example:

version(D_NET)
{
import System;
import dnet;
}
else
{
import std.stdio;
}

void main()
{
int [string] x;

x["one"] = 1;
x["two"] = 2;

foreach (k, v; x)
{
version(D_NET)
{
Console.WriteLine("{0}, {1}".sys, k, v);
}
else
{
writefln("%s, %d", k, v);
}
}
}

So I hacked the front-end of the D for .NET compiler to predefine D_NET.

Of course, abusing conditional compilation will yield code that is unreadable and hard to grasp as a C++ source littered with #ifdef ... #else ... (or the US tax code).

But I am a strong supporter of The Second Amendment of the Internet Constitution: "the right of the People to keep and bear compilers that let them shoot themselves in the foot shall not be infringed".

No comments: