Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Procedures and Modules

Fortran Modules and the use Statement

Organize Fortran code with modules: share constants, variables and procedures, control visibility with private and public, rename with use, and compile in order.

A module is Fortran's unit of code reuse. It bundles constants, variables, types and procedures under one name, and other program units pull them in with use. Modules replace the old common blocks and external procedures, and they give every call an explicit interface so the compiler checks your arguments.

If you have used namespaces, packages or header files in other languages, a module is the Fortran counterpart, with the extra benefit that its procedures are compiled together with their interfaces.

A first module

FORTRAN
module geometry
  implicit none
  real, parameter :: pi = 3.14159265

contains

  pure function circle_area(r) result(a)
    real, intent(in) :: r
    real :: a
    a = pi * r**2
  end function circle_area

  pure function rect_area(w, h) result(a)
    real, intent(in) :: w, h
    real :: a
    a = w * h
  end function rect_area

end module geometry

A program uses it like this:

FORTRAN
program shapes
  use geometry
  implicit none
  print *, circle_area(2.0)
  print *, rect_area(3.0, 4.5)
end program shapes

use geometry must come before implicit none and before any declarations. A module has two parts: a specification part (everything before contains: constants, variables, types) and a module procedure part (after contains). One implicit none at the top of the module covers all of its procedures.

Controlling what is visible

By default everything in a module is public. Good practice is to flip that default and export only what users need:

FORTRAN
module counter_mod
  implicit none
  private                       ! default: hidden
  public :: increment, current  ! the interface

  integer :: count = 0          ! hidden module state

contains

  subroutine increment()
    count = count + 1
  end subroutine increment

  integer function current()
    current = count
  end function current

end module counter_mod

Code that uses counter_mod cannot touch count directly. It must go through increment and current. That is information hiding: you may later change how the count is stored without breaking any caller.

protected is a middle path: a variable that users can read but not assign.

FORTRAN
integer, protected :: max_items = 100
Python Stand-in: a module with private state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Selecting and renaming with use

use module imports every public name. You can narrow or rename:

FORTRAN
use geometry, only: circle_area          ! import just one name
use geometry, only: area => rect_area    ! import under a new name
use geometry, pi_value => pi             ! import all, but rename pi

Prefer only:. It documents where each name comes from, avoids clashes, and speeds up compilation. A good habit: if a program uses five names from a module, list those five.

Why modules?

Reuse One definition, many users
Checked calls Explicit interfaces for free
Hiding private and protected
1 / 2

Compiling modules: the order matters

When the compiler processes module geometry it writes a .mod file describing the interfaces. Any file that says use geometry needs that .mod file, so the module must be compiled first:

TEXT
gfortran -c geometry.f90      # produces geometry.o and geometry.mod
gfortran -c main.f90          # reads geometry.mod
gfortran geometry.o main.o -o shapes

Build tools such as make or fpm (the Fortran package manager) work out this order for you. Changing a module's interface means every file that uses it must be recompiled, which is why large projects keep module specification parts small and stable.

flowchart LR
    A["geometry.f90"] -->|compile| B["geometry.o<br/>geometry.mod"]
    B -->|use geometry| C["main.f90"]
    C -->|compile| D["main.o"]
    B --> E["link"]
    D --> E
    E --> F["shapes"]

The .mod file is the hand-off between compilation steps.

Module variables and state

Variables declared in a module's specification part persist for the whole run (they have the save attribute implicitly) and are shared by every unit that uses the module. This makes them handy for configuration, but global mutable state is a classic source of bugs. Prefer parameter constants, protected variables, or pass data explicitly.

Submodules, briefly

A large module can split the interface from the implementation with submodule, so changing a procedure body does not force recompiling every user. You declare an interface in the module and give its body in a separate submodule file. For most programs a plain module is enough.

Common mistakes

  • Putting use after implicit none (it must come first).
  • Compiling the user before the module, so the .mod file is missing.
  • Circular dependencies: module A uses B and B uses A. Break the cycle by moving shared definitions into a third module.
  • Leaving everything public, then discovering callers depend on internals.
  • Using use m without only: and getting a name clash with a local variable.
Python Stand-in: only and renaming

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the use statement go in a program unit?

    use statements come first, then implicit none, then declarations.
  2. 2. What does a bare private statement in a module specification part do?

    It changes the default accessibility to private, and you then list exports with public.
  3. 3. What does use geometry, only: area => rect_area do?

    The => syntax renames on import, and only: limits the import to that one name.
  4. 4. Why must a module be compiled before the files that use it?

    The compiler stores interface information in the .mod file, which use statements read.

Summary

  • A module holds constants, variables, types and procedures; use imports them.
  • Use private by default and public for the interface; protected allows read-only access.
  • only: and => control and rename imports.
  • Compile modules before their users; the .mod file carries the interface.
  • Avoid mutable module variables where you can.

Next: Interfaces and generic procedures