How to call C functions from D

Overview

The D programming language is compatible with the C language. This allows the programmer to use both languages simultaneously. In this answer, we'll learn to use the C program function from the D language.

Syntax

extern (C){
// call the C program file function
}
Syntax

In D, we use extern(C) to add access to C language program file to utilize its functionality from the D program file.

Example

//declare the c++ function in d
extern (C){ 
int display();
}
void main()
{
//calling the c program function and passing value in the parameter
    display();
}
Program example

Explanation

In the main.d file:

  • Line 2: We use extern(C) to get access to the C program file functionalities.
  • Line 3: We declare a display function from the C program file.

In the display.d file:

  • Lines 3–8: We declare a display function in which we add a message "C function got executed". When we execute the program, it will reflect this message in the output.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved