Using Modules
Modules are useful because all variables within them—which can include derived datatypes—can be accessed (unless designated as private
, see below) by any subprogram which references the module with a use
statement. In addition, at compilation time, calls to module subprograms are checked for compatibility with their declared interfaces, which is helpful in preventing bugs.
Note that many compilers require that the definition of a module precede its use. When a source file for a module is compiled, a .mod
file is created (Example: ifort -c my_module.f90
creates a file my_module.mod
). This file is needed for the compilation of all programs and subprograms that use
the module. Consequently the modules have to be compiled before everything else.
An example of a module, my_module.f90
, and a main program using it, demo.f90
, is given below. The module and program can also be combined into a single source file (in the order shown) and compiled that way. The main program as written will not work because it attempts to call a subroutine that is private to the module.