cfortranfortran77

Can an f77 subroutine be called from C?


In modern Fortran, we can call a subroutine from C by using C binding. E.g. The Fortran subroutine will look like this

subroutine my_routine(...) bind (C, name="my_routine")

However, if the fortran subroutine is an old f77 subroutine, this binding is presumably not an available solution. What would be the best alternative?


Solution

  • However, if the fortran subroutine is an old f77 subroutine, this binding is presumably not an available solution.

    It depends. Modern Fortran is largely backwards compatible with Fortran 77. Your F77 subroutine will not come with a bind attribute, but if you're willing to add one and compile it with a modern Fortran compiler then chances are pretty good that it will work just as you expect of code originally written for a newer Fortran version.

    On the other hand, what C interop brings to Fortran is standardization, not a new capability. People have been calling Fortran routines from C almost as long as people have been using C.

    The issue here is that the specifics are system and compiler dependent. If you don't rely on C interop, then you will need to accommodate your Fortran compiler's name-mangling and argument-passing conventions to successfully call Fortran-compiled functions from C code. These vary. There used to be a fair amount of tools and documentation for such activity. I imagine it's harder to find these days, but much of it should still work.

    What would be the best alternative?

    That depends on your specific constraints. If you're up for modifying the Fortran source and compiling with a modern compiler then I'd at least start with adding a bind attribute to the function, and see how that plays out.