Modules
Large programs can be organized in separate modules and procedures. Here is an
example. We store various mathematical and physical constants in a module named
constants_module
.
MODULE const_module
IMPLICIT none
PRIVATE
REAL, PUBLIC, PARAMETER :: pi = 3.14159265
REAL, PUBLIC, PARAMETER :: e = 2.71828182
END MODULE const_module
Now we write a program that uses the above module:
PROGRAM circ_area
USE const_module
IMPLICIT none
REAL :: rad = 5.0, area
area = pi*rad**2
PRINT *, "Area = ", area
END PROGRAM circ_area
The PRIVATE
keyword makes sure everything is private otherwise declared as
PUBLIC
. Private variables are accessible only to the module, while public
variables are accessible to the programs that uses it. There is also PROTECTED
keyword, which allows the variable to be accessible but the value cannot be
modified. Compile and run our module and program:
gfortran -c 11_const_module.f90
gfortran 11_circ_area.f90 11_const_module.o
./a.out
Modules need to be compiled before the program that uses it. If both are placed
in the same source file, the module should come before the program. Once the
module is compiled, it will create .o
and .mod
files. When we compile the
program, we only need to provide the .o
file for linking, the compiler will
find the .mod
files. If the files are on a different directory, specify via
-I<dir>
option.
gfortran -I./ 11_circ_area.f90
USE keyword
Rename a variable:
use const_module, math_pi => pi
Use only certain variables:
use const_module, only : pi
use const_module, only : pi, e
Last command is same as:
use const_module, only : pi
use const_module, only : e
Use pi and rename e:
use const_module, only : pi, log_base => e