Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

d programming

How to call global functions in C++ from D

Mohe Ud Din Sheikh


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);
Syntax for calling C++ global functions from D

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:

  • Line 5: We declare the function that will sum the values passed in the parameters.

In the main.d file:

  • Line 2: We use extern (C++) to link both files and then declare the function in the D program.
  • Line 7: We call the sum function and pass the value in the parameters.

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 command dmd main.d sum.o -L-lstdc++ && ./main.


d programming


Mohe Ud Din Sheikh
Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring