Fortran Modules
A module is a named container for constants, variables, types and procedures that other program units can use. Modules are the backbone of every modern Fortran code base: they organise code into logical pieces, give every procedure an explicit interface automatically, and control what is visible from outside.
Defining and using a module
A module has a specification part (declarations) and, after contains, its procedures. A program gets access with use module_name. In a real project each module usually lives in its own file; here everything is in one source, with the module before the program that uses it.
module geometry
implicit none
real, parameter :: pi = 3.14159265
contains
function circle_area(r) result(a)
real, intent(in) :: r
real :: a
a = pi * r**2
end function circle_area
function sphere_volume(r) result(v)
real, intent(in) :: r
real :: v
v = 4.0 / 3.0 * pi * r**3
end function sphere_volume
end module geometry
program main
use geometry
implicit none
print '(a, f8.3)', 'pi = ', pi
print '(a, f8.3)', 'circle area = ', circle_area(2.0)
print '(a, f8.3)', 'sphere volume = ', sphere_volume(2.0)
end program mainpi = 3.142
circle area = 12.566
sphere volume = 33.510
When the module is compiled, the compiler writes a .mod file describing its contents. Units that use the module read that file, so on the command line modules must be compiled before the code that uses them:
gfortran -c geometry.f90 # produces geometry.o and geometry.mod
gfortran -c main.f90 # reads geometry.mod
gfortran geometry.o main.o -o appBuild tools such as CMake and fpm (the Fortran Package Manager) work out this order for you.
use … only
use module, only: name1, name2 imports just the names you list. This documents where each name comes from and avoids clashes. You can also rename on import with local_name => module_name:
module physics_constants
use iso_fortran_env, only: real64
implicit none
integer, parameter :: dp = real64
real(dp), parameter :: c = 299792458.0_dp ! speed of light, m/s
real(dp), parameter :: g = 9.80665_dp ! standard gravity, m/s^2
real(dp), parameter :: big_g = 6.67430e-11_dp ! gravitational constant
end module physics_constants
program constants_demo
use physics_constants, only: dp, light_speed => c, g
implicit none
real(dp) :: t
t = 1.0_dp
print '(a, es12.5, a)', 'light travels ', light_speed * t, ' m in 1 s'
print '(a, f7.3, a)', 'a dropped stone falls ', 0.5_dp * g * t**2, ' m in 1 s'
end program constants_demolight travels 2.99792E+08 m in 1 s
a dropped stone falls 4.903 m in 1 s
Here big_g is not imported, and c is visible only as light_speed.
public and private
By default everything in a module is public. Good modules hide their internals: write private as the default and mark the intended interface public. Hidden names can still be used by the module's own procedures.
module counter_mod
implicit none
private ! everything is private unless listed below
public :: increment, current_count
integer :: count = 0 ! module variable: hidden state
contains
subroutine increment(by)
integer, intent(in), optional :: by
if (present(by)) then
count = count + by
else
count = count + 1
end if
call check_limit()
end subroutine increment
integer function current_count()
current_count = count
end function current_count
subroutine check_limit() ! private helper
if (count > 100) print '(a)', 'warning: counter above 100'
end subroutine check_limit
end module counter_mod
program use_counter
use counter_mod
implicit none
call increment()
call increment(by=50)
call increment(by=60)
print '(a, i0)', 'count = ', current_count()
end program use_counterwarning: counter above 100
count = 111
The program cannot touch count or check_limit directly; it must go through the public procedures. If it tried count = 0, the compiler would complain that count has no type, because the name isn't visible.
Note: Module variables keep their values for the whole run (they implicitly have the
saveattribute). They are global state, so use them sparingly: constants and type definitions are great in modules, mutable variables less so.
protected: read-only from outside
A protected module variable can be read by any unit that uses the module, but only the module itself can change it. That's a neat way to publish configuration that is set once:
module settings
implicit none
private
public :: grid_size, configure
integer, protected :: grid_size = 10
contains
subroutine configure(n)
integer, intent(in) :: n
grid_size = max(2, n)
end subroutine configure
end module settings
program use_settings
use settings
implicit none
print '(a, i0)', 'default grid: ', grid_size
call configure(64)
print '(a, i0)', 'configured: ', grid_size
end program use_settingsdefault grid: 10
configured: 64
Modules using modules
Modules can use other modules, which builds a layered design: a kinds module at the bottom, then constants, then utilities, then the physics:
module kinds
use iso_fortran_env, only: real64
implicit none
integer, parameter :: dp = real64
end module kinds
module vectors
use kinds, only: dp
implicit none
contains
pure function norm(v) result(n)
real(dp), intent(in) :: v(:)
real(dp) :: n
n = sqrt(sum(v**2))
end function norm
end module vectorsCircular dependencies (A uses B and B uses A) are not allowed. For very large modules, Fortran 2008 submodules let you split the implementation from the interface to avoid long recompilation chains.
Test yourself
Why should procedures normally be placed in modules?
- They run faster
- The compiler then knows their interfaces and checks every call
- Modules are required for any procedure
- Modules allow global goto
What does use stats, only: mean do?
- Imports everything from stats
- Imports only the name
meanfrom the module stats - Renames the module
- Makes
meanprivate
A protected module variable can be…
- read and written anywhere
- read anywhere, but modified only inside its module
- used only inside its module
- modified only by the main program