#author("2020-01-06T11:16:23+09:00","default:Miyashita","Miyashita")
#author("2020-01-06T11:17:52+09:00","default:Miyashita","Miyashita")
*module メモ [#pb96582a]
Fortran の module の使用方法のメモ.~
~
用途は色々あるが,特に subroutine の引数に構造体(type)が入る場合に定義の手間を省ける.~
用途は色々あるが,subroutine の引数に構造体(type)が入る場合に,その都度定義する手間を省ける点が大きい(と思う).~
例えば,下記のような mymod という module を作成したとする.
#codeprettify(lang-fortran){{
module mymod
    implicit none

    type mytype
        real*8 :: varA, varB
    end type 
end module mymod
}}
このファイルを
#codeprettify(lang-fortran){{
ifort -c mymod.f90 -o mymod.o
}}
などでコンパイルすれば,use "モジュール名" で 定義した type や subroutine などを使用することができる.~

この mytype を subroutine の引数として使う時は下記の通り.
#codeprettify(lang-fortran){{
!-----------------------------------------
program main
    use mymod ! implicit none の前に use 
    implicit none

    real*8 :: x,y
    type(mytype) :: foobar

    !適当に値を入れる
    x = 4.0d0
    y = 3.0d0

    !呼び出し
    call assign_mytype(x,y,foobar)

    !確認
    write(*,*) foobar%varA
    write(*,*) foobar%varB

end program
!-----------------------------------------
subroutine assign_mytype(x,y,foobar)
    use mymod  ! implicit none の前に use 
    implicit none
    
    real*8, intent(in) :: x,y
    type(mytype), intent(out) :: foobar

    !構造体の変数に値を割り当てる
    foobar%varA = dsqrt(x*x + y*y)
    foobar%varB = (x-y)/(x+y)

    return
end subroutine 
!-----------------------------------------
}}
実行結果は
   5.00000000000000     
  0.142857142857143 
となる.~
肝心なのは,use "モジュール名" を implicit none の前に入れること.~

Front page   Edit Diff Attach Copy Rename Reload   New List of pages Search Recent changes   Help   RSS of recent changes