Reading — step 1 of 5
Learn
~1 min readModules and Subprograms
A module in modern Fortran is a namespace + interface unit. Use it to group related procedures, types, and constants.
module math_utils
implicit none
private
public :: square, sum_array, PI
real, parameter :: PI = 3.14159265
contains
pure function square(n) result(s)
integer, intent(in) :: n
integer :: s
s = n * n
end function
pure function sum_array(a) result(s)
integer, intent(in) :: a(:)
integer :: s
s = sum(a)
end function
end module
private / public — control what's exported. By default everything in a module is public.
use brings module contents into scope:
program main
use math_utils
implicit none
print *, square(7)
print *, PI
end program
Selective import with only:
use math_utils, only: square
Renaming:
use math_utils, only: sq => square
print *, sq(7)
Why modules matter:
- Type-checked interfaces — compile-time errors instead of segfaults
- Encapsulation
- Compiler can optimize aggressively across module boundaries
- Replaces older
externalandcommonblocks
Modules are stored in .mod files alongside object files. Compile order matters — modules must be compiled before code that uses them.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…