Fortran Wiki


Modules are used for object oriented programming.

General form

The general form is

module <name>
  <use statements>  
  <subroutines and functions>
end module <name>

Data access

There are three possible access properties: public, private, protected.

  • public: Outside code has read and write access.
  • private: Outside code has no access.
  • public, protected: Outside code has read access.

Using module in other code

One can include the module’s public data in outside code. There are three ways.

  • use <moduleName>: includes all public data and methods
  • use <moduleName>, <renames>: includes all public data and methods, but renames some public data or methods
  • use <moduleName>, only : <subset>: includes only some public data and methods


These examples highlight the above methods using the following module.

!> \\file test_module.f
module test_module
  implicit none
  integer, public :: a=1
  integer, public, protected :: b=1
  integer, private :: c=1
end module test_module

Data access

!> \\file main.f
program main
  use test_module

  ! accessing public object works
  print *, a

  ! editing public object works
  a = 2

  ! accessing protected object works
  print *, b

  ! editing protected object does not work
  !b = 2 <- ERROR

  ! accessing private object does not work
  !print *, c <- ERROR

  ! editing protected object does not work
  !c = 2 <- ERROR

end program main

Using module in other code

!> \\file main1.f
program main
  use test_module

  print *, a, b

end program main
!> \\file main2.f
program main
  use test_module, better_name => a

  ! new name use available
  print *, better_name

  ! old name is not available anymore
  !print *, a  <- ERROR

end program main
!> show using only
program main
  use test_module, only : a

  ! only a is loaded
  print *, a

  ! b is not loaded
  !print *, b  <- ERROR

end program main