D programs generally require:
To link D functions and libraries into C programs, it's necessary to only require the C runtime library to be linked in. This is accomplished by defining a subset of D that fits this requirement, called BetterC.
When BetterC is enabled, the predefined Conditional Compilation D_BetterC can be used for conditional compilation.
An entire program can be written in BetterC by supplying a C main() function:
extern(C) void main() { import core.stdc.stdio : printf; printf("Hello betterC\n"); }
> dmd -betterC hello.d && ./hello Hello betterC
Limiting a program to this subset of runtime features is useful when targeting constrained environments where the use of such features is not practical or possible.
BetterC makes embedding D libraries in existing larger projects easier by:
Note: BetterC and ImportC are very different. ImportC is an actual C compiler. BetterC is a subset of D that relies only on the existence of the C Standard library.
Nearly the full language remains available. Highlights include:
While testing can be done without the -betterC flag, it is sometimes desirable to run the testsuite in -betterC too. unittest blocks can be listed with the getUnitTests trait:
unittest { assert(0); } extern(C) void main() { static foreach(u; __traits(getUnitTests, __traits(parent, main))) u(); }
> dmd -betterC -unittest -run test.ddmd runpezoXK
foo.d:3: Assertion `0' failed.
However, in -betterC, assert expressions don't use Druntime's assert and are directed to assert from the C runtime library instead.
D features not available with BetterC:
simd, Vector Extensions, importc, ImportC
Linking
It is straightforward to link C functions and libraries into D programs. But linking D functions and libraries into C programs is not straightforward.