Better C
It is straightforward to link C functions and libraries into D programs. But linking D functions and libraries into C programs is not straightforward.
D programs generally require:
- The D runtime library (Phobos) to be linked in, because many features of the core language require runtime library support.
- The main() function to be written in D, to ensure that the required runtime library support is properly initialized.
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 version 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:
- Simplifying the process of integration at the build-system level
- Removing the need to ensure that Druntime is properly initialized on calls to the library, when an initialization step is not performed before the library is used.
- Mixing memory management strategies (GC + manual memory management) can be tricky, hence removing D's GC from the equation may be a good solution.
Retained Features
Nearly the full language remains available. Highlights include:
- Unrestricted use of compile-time features
- Full metaprogramming facilities
- Nested functions, nested structs, delegates and lambdas
- Member functions, constructors, destructors, operating overloading, etc.
- The full module system
- Dynamic arrays, array slicing, and array bounds checking
- RAII (yes, it can work without exceptions)
- scope(exit)
- Memory safety protections
- Interfacing with C++
- COM classes and C++ classes
- assert failures are directed to the C runtime library
Not Available
D features not available with BetterC:
- Garbage Collection
- Thread-local storage
- TypeInfo and ModuleInfo
- Classes
- Built-in threading (e.g. core.thread)
- Dynamic arrays (but not slices) and associative arrays
- Exceptions
- switch with strings
- final switch
- synchronized and core.sync
- Static module constructors or deconstructors
- Struct deconstructors
- unittest (testing can be done without the -betterC flag)