Program structure

Program units

Fortran code is organized in program units: the main program, modules, subroutines, and functions.

Small scripts need only a program. Larger projects move shared data and procedures into modules that the program loads with use.

module tools implicit none contains subroutine greet() implicit none print *, "Hello from a module" end subroutine greet end module tools

host association

The contains keyword splits a program unit into a declaration part above it and procedures below it.

Procedures below contains can see the names declared above, which is called host association. Use it for small helpers that belong to one program.

program hostdemo implicit none integer :: n n = 3 call show() contains subroutine show() implicit none print *, "n =", n end subroutine show end program hostdemo

Order of statements

Each unit follows the same order: header line, use statements, implicit none, declarations, executable code, then contains with procedures.

Declarations always come before executable statements. The compiler rejects code that mixes them in the wrong order.

program orderdemo implicit none integer :: x x = 10 print *, "x =", x end program orderdemo

Style that scales

Indent the body by two spaces, give procedures clear names, and keep one idea per line.

Place shared constants and helpers in a module early, so the main program stays short and easy to read as the project grows.

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

Banner image