Modules
| Define a module | |
| Use it | |
| Public vs private | |
| Compile order |
Define a module
A module is a package of procedures and data: it opens with module, shares its contents after contains, and closes with end module.
Everything inside one module sees everything else, and every user of the module gets an explicit interface for free.
module stats
implicit none
contains
integer function double_it(x)
implicit none
integer, intent(in) :: x
double_it = x * 2
end function double_it
integer function triple(x)
implicit none
integer, intent(in) :: x
triple = x * 3
end function triple
end module stats
Use it
The use statement imports a module into a program: after use stats every public procedure is callable by name.
Keep the module in stats.f90 and the program in main.f90, then build both files together.
program usedemo
implicit none
use stats
print *, double_it(20)
print *, triple(14)
end program usedemo
gfortran stats.f90 main.f90 -o demo && ./demo
40
42
Public vs private
Private hides the helpers while public opens the front door: start with private, then export only the names callers need.
Callers of vault can reach open_it but cannot touch secret, so internals stay free to change.
module vault
implicit none
private
public :: open_it
contains
subroutine open_it()
implicit none
print *, "open"
end subroutine open_it
subroutine secret()
implicit none
print *, "shut"
end subroutine secret
end module vault
Compile order
Modules must be compiled before their users: list the provider file first so the module file is ready when the user needs it.
Reversed order fails fast with a missing module file error, which points straight at the ordering mistake.
program vaultdemo
implicit none
use vault
call open_it()
end program vaultdemo
gfortran main.f90 stats.f90 -o demo
Fatal Error: Cannot open module file 'stats.mod' for reading
Next: USE with ONLY
Article author: Arthur Isaev