How to call global functions in C++ from D

Overview

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.

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.

Example

//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);
}
Program example for calling C++ global functions from D

Explanation

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.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved