1

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.

Justin
  • 11
  • 2
  • 2
    Include the fortran runtime library in the link. `-lgfortran`, I believe, since you're using the GNU suite. – John Bollinger Feb 18 '23 at 00:56
  • @JohnBollinger That appears to have worked. However, I notice that I have to include `-lgfortran` as the last argument to the linker or it gives the same error. E.g. `gcc test.o main.o -lgfortran` works, while `gcc -lgfortran test.o main.o` does not. Can you help me understand why? – Justin Feb 18 '23 at 02:08
  • 1
    Linker flag are not just like any compiler flags but they are often order dependent, especially for static libraries. See https://stackoverflow.com/questions/45135/why-does-the-order-in-which-libraries-are-linked-sometimes-cause-errors-in-gcc https://stackoverflow.com/questions/11893996/why-does-the-order-of-l-option-in-gcc-matter – Vladimir F Героям слава Feb 18 '23 at 05:51

0 Answers0