Skip to content
Modules
step 1/5

Reading — step 1 of 5

Learn

~2 min readSubroutines, Functions, Format I/O

Modules are Fortran's namespace and code organization unit. They contain types, functions, and module variables — used across multiple programs.

Defining a module

module my_math
    implicit none
    public :: square, cube
    private :: helper                    ! optional — not exported

    real, parameter :: pi = 3.14159265

contains

    function square(x) result(r)
        real, intent(in) :: x
        real :: r
        r = x * x
    end function square

    function cube(x) result(r)
        real, intent(in) :: x
        real :: r
        r = x * x * x
    end function cube

    function helper() result(r)
        real :: r
        r = 0.0
    end function helper

end module my_math
  • public :: lists exported names (default in many compilers)
  • private :: lists non-exported names
  • Top-level private (no list) makes everything private by default — opt in with public ::
  • parameter — compile-time constant

Using a module

program demo
    use my_math
    implicit none

    print *, square(5.0)
    print *, pi
end program demo

Selective import:

use my_math, only: square, cube

Renaming:

use my_math, only: sq => square

Module variables

module counter
    implicit none
    integer :: count = 0           ! shared module variable

contains

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

end module counter

count is shared across all users of the module — careful with global state.

Module hierarchies

module physics_constants
    real, parameter :: c = 2.998e8       ! speed of light
    real, parameter :: g = 6.674e-11
end module

module physics_calculations
    use physics_constants
    ...
end module

Compile dependencies follow use statements. Build systems (CMake, fpm) handle this automatically.

Why modules matter

Before modules (FORTRAN 77), code was organized via common blocks (shared memory) and include directives. Modules add type safety, namespace control, and clean compilation.

Modern Fortran codebases are heavily modular — projects like MKL (Intel Math Kernel Library), NetCDF, and atmospheric models use thousands of modules.

In Judge0

Single-file submissions can put modules ABOVE the main program in the same file:

module mymod
    ...
end module mymod

program main
    use mymod
    ...
end program main

No separate compilation needed.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…