Calling Fortran subroutines in C program

Many numerical software packages are written in Fortran. Very often, we would like to call Fortran subroutines in C programs.

A Fortran subroutine is compiled by a Fortran compiler. When calling Fortran subroutines in a C program, we must follow system dependent naming convertions. For example, in SUN systems, an underscore suffix is added to each Fortran subroutine name. Suppose a file decomp.f contains a Fortran subroutine nameddecomp, then

% f77 -c decomp.f

generates an object code named decomp.o containing decomp_, which can be called by a C program. For example, suppose a C program eg.c calls decomp_ and it has been compiled and eg.o has been generated. Then

% gcc -o eg eg.o decomp.o

generates an executable eg.
 

Fortran passes arguments by references. Thus we must use pointers when calling Fortran subroutines in a C program. Also, since Fortran subroutines do not return values, results must be returned through arguments using pointers.
 
  C            Fortran
-------------------------
  float           real
  double          real*8
The index of a Fortran array starts with 1 whereas that of C starts with 0.  As to multi-dimensional arrays, for example, When storing a two dimensional array in memory, C follows "row first", but Fortran is "column first". For example, a 2-by-2 array in C would create the following memory map:
     A[0][0] , A[0][1], A[1][0], A[1][1].
But Fortran would create:
     A[1][1] , A[2][1], A[1][2], A[2][2].
Therefore, when we pass the pointer of an array in C to a Fortran routine, we need to transpose the array before and/or after the Fortran routine in order to match the different styles between C and Fortran.

Find out more

1. User Notes on FORTRAN Programming (UNFP)
2. Binding C and FORTRAN Source Code
3. The C/FORTRAN Interface Kit
4. Fortran FAQ