Fortran include statement

The Fortran include statement inserts source code from the specified file into the Fortran source code file at the location of the include statement. The include file can contain any valid Fortran syntax, including procedures, modules, variable definitions, operations, etc. This concept is similar to the C/C++ #include preprocessor directive that can also be used for inlining code, but Fortran include does not require a preprocessor. include statements are frequently used to reuse code like defining constants or Fortran 77 common blocks. Generated code from build systems like CMake and Meson can be consumed with include statements. The file suffix “.inc” is often used, but is arbitrary.

One example of a Fortran-only project extensively using CMake-generated Fortran source with include is h5fortran to allow polymorphic (type and rank) HDF5 I/O in Fortran. The source code deduplication thus achieved is significant and the code is easier to maintain.

Build systems scan Fortran source files for dependencies to detect the include statements and track the included files. Makefiles with CMake uses the compiler itself or depend.make in each target build directory to track dependencies. Ninja (with CMake or other build system such as Meson) specifies include dependencies via depfiles per source file, which may be observed for debugging with option ninja -d keepdepfile

In the example below, the dependency of main.f90 on const.inc is tracked by:

  • Ninja: depfile “build/CMakeFiles/main.dir/main.f90-pp.f90.d”
  • Make: “build/CMakeFiles/main.dir/depend.make”

A minimal example of using the Fortran include statement is shown below.

main.f90:

program main

include 'const.inc'

print '(A, I0)', 'The value of my_const is: ', my_const

end program

const.inc:

integer, parameter :: my_const = 42

CMakeLists.txt:

cmake_minimum_required(VERSION 3.20)

project(include_example LANGUAGES Fortran)

add_executable(main main.f90)

Observe that CMake will rebuild main.f90 if const.inc changes.

cmake -Bbuild
cmake --build build

touch const.inc

cmake --build build