Wrap Fortran code to use in C++

There’s a lot of useful code in Fortran, and a lot of people actually prefer to work in Fortran, so as a C++ developer, it would be nice to be able to call their code from C++. Here’s a small CMake example for how to do it so you can follow along below: Download

I put the example together and tested it with the following versions of these tools:

  • g++ 4.7.3
  • gfortran++ 4.7.3
  • cmake 2.8.10.1

From a high level, the example does the following:

  1. Create a one-function Fortran library.
  2. Set up the interface to the Fortran library in C++ code.
  3. Link to the Fortran library and call the Fortran function.

Something to note is that all the parameters to Fortran function is a pointer type, even for non-array data types.

To demystify the part of the example that sets up the interface to Fortran code:

extern "C" 
{
    void average_(int *n, double *a, double *ave);
}

The extern "C" part tells the C++ compiler not to expect a mangled name but rather take the function name as it is. C++ renames function names at compile-time in order to support function overloading automatically, but this behavior should be disabled when interfacing with code from other languages like Fortran.

Note that the average function has an underscore appended to it, whereas it does not have it in the Fortran file where it is defined. This is default behavior of gfortran. I think I read that there is a flag to disable this behavior, but I think it’s nice to make it clear that it is a Fortran function.

Advertisements