Posts Tagged ‘C’

Automatic generation of a C header from Fortran code?

Saturday, October 31st, 2009

Dear Lazyweb,

In my newest project I need to use Fortran routines and variables in C. From the source code point of view this requires only to declare the needed Fortran entities in your C code whilst taking the “right” types of the variables and the name mangling of the Fortran compiler into account.

Here is an example. Consider you have the following Fortran code:

module X
  real, dimension(0:1) :: v
 
  subroutine Foo(A, b, c, &
    & D)
    integer, intent(in) :: a, &
      & B
    real, intent(out) :: C, d
    ! <Foo's body>
  end subroutine
end module X

To use the array v and the subroutine Foo() in C, you need to add (something like) the following declarations to your C source code:

extern float x_mp_v_[2];
 
void x_mp_foo_(int* a, int* b, float* c, float* d);

If only a handful of Fortran routines are needed to be called from C, declaring them by hand may be feasible. This is however error-prone and becomes impracticable for more than a handful of routines. Especially if the routine signatures change frequently.

So what I’d like to have is a tool that generates a C header file containing all declarations of Fortran entities from a given Fortran source file. Or if such tool does not exist, a tool that extracts variable declarations and routine signatures from a Fortran source file into a format that is easier to parse than Fortran itself would also be helpful. Any suggestions?