This example demonstrates how to call C functions from Fortran.
fortranCopy codemodule interface
use iso_c_binding, only: c_int, c_double, c_null_ptr, c_f_pointer
implicit none
interface
function c_function(x) bind(c)
import :: c_double
real(c_double) :: c_function
real(c_double), value :: x
end function c_function
end interface
end module interface
program call_c
use interface
implicit none
real(c_double) :: result
result = c_function(3.0)
print *, 'Result from C function: ', result
end program call_c
In the above example, you would need a C function defined as follows and compiled with the Fortran code:
cCopy code#include <stdio.h>
double c_function(double x) {
return x * x;
}
Compile the C code into a shared library and link it with the Fortran program.
Interfacing with C Code