モジュール - modules(Fortran 第9回)

←第8回 内部ルーチン・内部関数

はじめに

第9回はモジュールです。
ひとまず、Fortranの内容は今回で終了です。サブグループの内容がわかっていれば、さほど難しくありません。

モジュールとは

モジュールとは、変数や手続き(内部ルーチン)などの様々な要素をひとまとめにしたものでです。モジュールを使うことによって、カプセル化やデータの共有を行うことができます。また、モジュール間では同じ名前の要素が作成できるため、名前空間の切り分けにも利用できます。

モジュールの解説

以下の具体例で示しているように、モジュールは外部ルーチンのようにmain programの外部に記述します。手続き(サブルーチン)を記述する際は、モジュール内部でcontainsして内部ルーチン(内部関数)として記述します。main programでモジュールの要素を利用する場合は、main programの冒頭にuse (モジュール名)でモジュールを利用できるようにしておきます。

具体例(モジュール)

! Module definition
module BasicCalculation
    implicit none
    private ! All variables and procedures are private by default

    ! Public constants and parameters
    integer, parameter :: VERSION =   1

    ! Public procedures
    public :: add, subtract

contains
    ! Function to add two integers
    pure function add(a, b) result(r)
        integer, intent(in) :: a, b
        integer :: r
        r = a + b
    end function add

    ! Subroutine to subtract two integers
    subroutine subtract(a, b, difference)
        integer, intent(in) :: a, b
        integer, intent(out) :: difference
        difference = a - b
    end subroutine subtract
end module BasicCalculation

! Program that uses the BasicCalculation module
program CalculationProgram
    use BasicCalculation
    implicit none

    integer :: num1, num2, sum, diff

    num1 =   5
    num2 =   3

    ! Use the add function from the module
    sum = add(num1, num2)
    print *, 'Sum: ', sum

    ! Use the subtract subroutine from the module
    call subtract(num1, num2, diff)
    print *, 'Difference: ', diff
end program CalculationProgram

まとめ

第9回はモジュールについて解説しました。
このページでは、モジュール自体の概念が理解しやすいように、単純な例しか扱っていないので、自分でコードを書いてみたり、ネットに転がっているコードを読んでみたりして理解を深めましょう。

注意

このページは大学のFortranの授業の予習で書いています。
直観的な理解をメモしているだけなので、厳密なところでは誤りがあるかもしれません。

←第8回 内部ルーチン・内部関数