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:
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.
Implementation Defined: BetterC is typically enabled by setting the -betterC command line flag for the implementation.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:
Nearly the full language remains available. Highlights include:
scope(exit)
assert
failures are directed to the C runtime libraryswitch
with stringsfinal switch
unittest
-betterC
-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.d dmd_runpezoXK: foo.d:3: Assertion `0' failed.However, in
-betterC
assert
expressions don't use Druntime's assert and are directed to assert
of the C runtime library instead. D features not available with BetterC:
core.thread
)synchronized
and core.sync
© 1999–2019 The D Language Foundation
Licensed under the Boost License 1.0.
https://dlang.org/spec/betterc.html