Modules

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 use stats implicit none 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 use vault implicit none call open_it() end program vaultdemo

gfortran main.f90 vault.f90 -o demo

Fatal Error: Cannot open module file 'vault.mod' for reading at (1): No such file or directory

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev