Is it possible? i.e. compile .c with dmc and .d with dmd and then link them together, will this work? Will I be able to call D functions from C code, share globals etc? Thanks.
The C++ language provides mechanisms for mixing code that is compiled by compatible C and C++ compilers in the same program. You can experience varying degrees of success as you port such code to different platforms and compilers.
Just declare the C++ function extern "C" (in your C++ code) and call it (from your C or C++ code). For example: // C++ code: extern "C" void f(int);
Code structure of both the languages are same. The compilation of both the languages is similar. They share the same basic syntax. Nearly all of C's operators and keywords are also present in C++ and do the same thing.
Yes - C++ can use C libraries. Except of course that you're using the C++ version of cstdio . To use the C one you need to #include <stdio. h> .
Yes it is possible. In fact this is one of the main feature of dmd. To call a D function from C, just make that function extern(C)
, e.g.
// .d
import std.c.stdio;
extern (C) {
shared int x; // Globals without 'shared' are thread-local in D2.
// You don't need shared in D1.
void increaseX() {
++ x;
printf("Called in D code\n"); // for some reason, writeln crashes on Mac OS X.
}
}
// .c
#include <stdio.h>
extern int x;
void increaseX(void);
int main (void) {
printf("x = %d (should be 0)\n", x);
increaseX();
printf("x = %d (should be 1)\n", x);
return 0;
}
See Interfacing to C for more info.
The above answer is wrong as far as I know. Because the D main routine has to be called before you use any D functions. This is necessary to "initialize" D, f.e. its garbage collection. To solve that, you simply can make the program be entered by a main routine in D or you can somehow call the D main routine from C. (But I dont know exactly how this one works)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With