I'm trying to write a Fortran routine that can be called from a C program. The Fortran code compiles correctly, but when I try to link the C code against the Fortran binary, I get an error saying there's an undefined reference to a Fortran intrinsic routine. Is it possible to write either the Fortran code itself, or its C interface definition, such that a Fortran function that calls a Fortran intrinsic can be called from C? If so, how is this done?
The Fortran code that I want to call from C is in a file called "test.f90":
module test
use, intrinsic :: iso_c_binding, only : c_double
implicit none
contains
function getRand() bind(c)
real(c_double) :: getRand
call random_number(getRand)
end function getRand
end module test
The C code that I want to execute this code is in a file called "main.c":
extern double getrand();
int main(){
double r = 0.0;
r = getrand();
return 0;
}
I tried to build the code with the following commands:
>$ gfortran -c test.f90
(This executed with no error)
Then I ran:
>$ gcc test.o main.c
This command failed with the error message:
/usr/bin/ld: testmodule.o: in function `getrand':
testmodule.f90:(.text+0x15): undefined reference to `_gfortran_random_r8'
collect2: error: ld returned 1 exit status
I'm using gfortran and gcc versions 11.3.0 on Ubuntu 20.04.1, running on Windows WSL version 2. The linker is GNU ld version 2.38.