DJames
DJames

Reputation: 689

Calling a subroutine in a module from C

I would like to know how I can get a C program to call a Fortran 90 subroutine contained withing a Fortran 90 module.

This question deals with a similar problem, and I'm trying to implement the solution, but I'm still having issues.

Here are toy examples of the testC.c file, which contains the main function, and the module file testF.f90, which contains the Fortran 90 subroutine.

testC.c

#include <stdlib.h>
#include <stdio.h>

extern void __testF_MOD_fortfunc(int *,float *);

int main() {
   int ii=5;
   float ff=5.5;

   __testF_MOD_fortfunc(&ii, &ff);

   return 0;
}

testF.f90

module testF

contains

subroutine fortfunc(ii,ff)
    implicit none

    integer ii
    real*4  ff

    write(6,100) ii, ff
    100 format('ii=',i2,' ff=',f6.3)

    return
end subroutine fortfunc

end module testF

To compile, I am using the following lines

gcc -c testC.c
gfortran -o testF.f90
gcc -o test testF.o testC.o -lgfortran

I get the error message

testC.o: In function `main':
testC.c:(.text+0x27): undefined reference to `__testF_MOD_fortfunc'
collect2: error: ld returned 1 exit status

Upvotes: 1

Views: 1039

Answers (1)

Alexander Vogt
Alexander Vogt

Reputation: 18098

You can use objdump -t testF.o to read out the function name from an object directly. This reveals the following line:

0000000000000000 g     F .text  00000000000000b4 __testf_MOD_fortfunc

That's your function name. You can see that it is testf in lowercase. Using this in the C code should solve your problem.

However, these naming conventions are compiler dependent. You should really take a look into the ISO_C_binding module and the improved C interoperability of modern Fortran.

Upvotes: 3

Related Questions