Build with gfortran and make

-Wall -Wextra -fcheck

Strict flags turn silent bugs into loud compile time errors. Wall and Wextra enable useful warnings while fcheck adds runtime checks for bounds and more. Keep them on for debug builds from day one.

program app implicit none integer :: n n = 42 print *, "n =", n end program app

gfortran -Wall -Wextra -fcheck=all -g app.f90 -o app

./app

n = 42

-J module dir

Modules compile to .mod files that other units import at build time. The -J flag chooses the directory for those files so build roots stay clean. The -I flag tells later compiles where to find them.

Here the module sits in utils.f90 and the program in main.f90, which uses it.

module utils implicit none contains integer function answer() implicit none answer = 42 end function answer end module utils

program app use utils implicit none print *, "n =", answer() end program app

mkdir -p build_mods

gfortran -J build_mods -c utils.f90

gfortran -I build_mods main.f90 utils.o -o app

Minimal Makefile

A minimal Makefile rebuilds only stale files with one word: make. List object files as prerequisites of the app target and add a pattern rule for compiling. A clean target removes build artifacts. Recipe lines below start with a tab character, which make requires.

One extra line makes the module build first: main.o needs utils.o, so the .mod file exists before the program is compiled.

The clean target also clears the objects of the manual build above, so the next run starts from an empty tree.

FC = gfortran FFLAGS = -Wall -Wextra -fcheck=all app: main.o utils.o $(FC) $(FFLAGS) main.o utils.o -o app main.o: utils.o %.o: %.f90 $(FC) $(FFLAGS) -c $< -o $@ clean: rm -f app *.o *.mod .PHONY: clean

make clean

make

gfortran -Wall -Wextra -fcheck=all -c utils.f90 -o utils.o
gfortran -Wall -Wextra -fcheck=all -c main.f90 -o main.o
gfortran -Wall -Wextra -fcheck=all main.o utils.o -o app

fpm concept

The Fortran package manager fpm wraps this workflow in standard commands. Fpm new starts a layout, fpm build compiles, and fpm test runs the suite. Learn the concept here and install the tool when a project outgrows plain makefiles: it is not part of gfortran, so the commands below are not run on this page.

fpm new demo

fpm build

fpm test

The code on this page was run with gfortran 15.2.0 and GNU Make 4.4.1 on Alpine Linux 3.24 (x86_64) in a Docker container; the fpm commands need the Fortran package manager, which is not installed here.

Article author: Arthur Isaev