If I import the std.c libaries instead of including the libraries in C, would C code compile with a D compiler, or are there other backwords compatibility issues?
Is D backwards compatible with C if you use the C libraries?
575 views Asked by Orcris AtThere are 3 answers
Your question is different from the one you ask in the OP body.
Q1: Is D backwards compatible with C if you use the C libraries?
A: Yes. You can use C libraries. More about this here.
Q2: Would C code compile with a D compiler?
A: It was never intention for an implementation of D compiler to be able to compile C code. However, lots of C code would compile because D matches C compiler's data types, layouts, and function call/return sequences. As Zor pointed out C-style function pointer syntax, and C-style array pointer syntax has been deprecated.
You're never going to be able to take a C or C++ file and compile at as D code, and you can't just #include
C headers in D. D is not backwards compatible with either C or C++. Rather, it's possible to declare extern(C)
functions in your D code and call those C functions as if they were D functions (naturally, you then have to link with the C library that they're defined in). See
for details on calling C code from D.
druntime (which contains the core.* modules) has declarations for quite a few of the standard C and OS functions (in the core.stdc.* and core.sys.* modules), but you'll have to look at the druntime files yourself to see what they are, because they're not properly documented at this point. For any other C functions that you want to call, you can easily create declarations for them yourself, as described in the links above.
Now, C and D are very similar syntactically, so some sections of C code will compile just fine as D code, but programs as a whole will not. The general rule is that C/C++ code will either compile as valid D code with the same semantics, or it won't compile as D code. There are a few cases where that isn't true (e.g. static arrays are value types in D, unlike C/C++), but it is in almost all cases. This makes porting C/C++ code to D fairly easy, but it was never intended that D be backwards compatible with C code in the way that C++ is.
There are several subtleties in D that can make C code not behave exactly as you may want it to. For instance, integer promotion rules are not quite the same (but almost), and initialization rules are different (floating point values -- including arrays of such -- are initialized to NaN, for example). Further, C function pointer syntax was deprecated recently, so you might have to translate some C type syntax to the equivalent D syntax.
In general, though, there is great focus on backwards compatibility, and most C code should compile fine (or with a very minor amount of changes) in D with the same semantics as in C.
Also note that
std.c
is deprecated; please usecore.stdc
instead.