I think in modern Fortran code other than that in the main program should be in modules, but there is much code that does not follow this convention. John Burkardt does not use modules in his vast Fortran 90 collection. His source files do contain multiple related procedures, so the obvious fix is to put
module m
contains
at the top and
end module m
at the bottom of such files. However, typically some declarations need to be removed. Here is an illustration. The code
function square(i) result(i2)
implicit none
integer, intent(in) :: i
integer :: i2
i2 = i**2
end function square
function cube(i) result(i3)
implicit none
integer, intent(in) :: i
integer :: i3
integer :: square
i3 = i * square(i)
end function cube
program main
implicit none
integer :: cube
print*,cube(5)
end program main
compiles and runs. The equivalent code with a module that compiles and runs is
module m
contains
function square(i) result(i2)
implicit none
integer, intent(in) :: i
integer :: i2
i2 = i**2
end function square
function cube(i) result(i3)
implicit none
integer, intent(in) :: i
integer :: i3
! integer :: square
i3 = i * square(i)
end function cube
end module m
program main
use m
implicit none
! integer :: cube
print*,cube(5)
end program main
In function cube
the declaration integer :: square
must be removed. If it is not, you get an error message such as
xmodule.f90:(.text+0x1a): undefined reference to
square_’`
where xmodule.f90 is the file containing all the code. So to transform a Fortran code that is comprised of multiple source files to one in which procedures are in modules, one needs to
(1) put the code in each source file in a module. My convention is that a file foo.f90 contains module foo_mod.
(2) remove declarations of called functions in the caller, as shown above
(3) add the appropriate use foo_mod statement in the caller, for procedures invoked from other modules or the main program
I wonder if there are tools for this. It would be great if Burkardt’s codes could be organized into hundreds of modules and the demonstration programs USEd those modules.