Skip to content

Instantly share code, notes, and snippets.

@dmentipl
Last active June 28, 2019 07:24
Show Gist options
  • Save dmentipl/f88c8f713d0220368d5d4face95eeb67 to your computer and use it in GitHub Desktop.
Save dmentipl/f88c8f713d0220368d5d4face95eeb67 to your computer and use it in GitHub Desktop.
Fortran issues with renaming subroutines when using from modules

Fortran issues with renaming subroutines when using from modules

There are issues with naming a subroutine the same as a subroutine that is used from another module but is renamed. See the code for details.

Instructions

Download all files in this gist.

To see the bug in the code, compile with gfortran-7:

make FC=gfortran-7
./prog

It should hang, and leak memory.

Try again with a newer gfortran:

make FC=gfortran-8
./prog

This should finish immediately and print

   2.00000000

Issue

The issue is that even when renaming a subroutine used from a module you cannot name a subroutine, locally, with the same original name as the used subroutine. At least with a gfortran version earlier than 8.

Solution

Use gfortran-8 or greater. Or don't use name a subroutine with the same name as another even if renaming when using from the other module.

In the latter case, in lib.f90 replace

subroutine subr

with, for example,

subroutine subr_c

And in prog.f90 replace subr with subr_c.

module lib
use modu, only: subr_f => subr
use iso_c_binding, only: c_float
implicit none
public :: subr
contains
subroutine subr(x, y) bind(c)
real(c_float), intent(in) :: x
real(c_float), intent(out) :: y
call subr_f(x, y)
end subroutine subr
end module lib
FC = gfortran
FCFLAGS = -O3
default: prog
mod:
$(FC) $(FCFLAGS) -c mod.f90
lib: mod
$(FC) $(FCFLAGS) -c lib.f90
prog: mod lib
$(FC) $(FCFLAGS) -o prog mod.o lib.o prog.f90
.PHONY:
clean:
\rm -rf *.o *.mod
module modu
implicit none
public :: subr
contains
subroutine subr(x, y)
real, intent(in) :: x
real, intent(out) :: y
y = 2*x
end subroutine subr
end module modu
program prog
use lib, only: subr
implicit none
real :: x, y
x = 1.0
call subr(x, y)
print*,y
end program prog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment