D programming language is compatible with C++, which helps us link both programming languages using extern(C++)
. After using this command, we can use the global function declared within the C++ file.
To use the global function, we first compile the C++ file separately. We can then call that function in our D program using the compiled C++ file.
Let’s explore the syntax.
extern (C++)int sum(int a, int b);
To call the C++ function from D, we use extern(C++)
. Then, we add the function we want to use in the C++ file.
//declare the c++ function in d extern (C++) int sum(int a, int b); void main() { //calling the funtion and passing value in the parameter sum(4, 22); }
In the sum.cpp file:
In the main.d file:
extern (C++)
to link both files and then declare the function in the D program.Note: To run this program locally, we have to compile the C++ file separately by using the command
g++ -c sum.cpp
in the terminal and then use the commanddmd main.d sum.o -L-lstdc++ && ./main
.
Free Resources