When does a module go out of scope in Fortran 90/95?

巧了我就是萌 提交于 2019-12-29 01:43:51

问题


My intended use is

program main
  use mod

  external sub

  call sub
end program main

subroutine sub
  ! code here calls subroutines in mod
end subroutine sub

Specifically, will module mod be in scope in subroutine sub? Also, I'd be interested to know more generally when a module is in/out of scope. I'm using gfortran 4.6.1, if it matters.


回答1:


It is not in scope of subroutine sub, as sub cannot call routines or use variables from mod, because sub is not part of the program main. They have nothing in common, are separate compilation units and only may call each other (if they are callable).

Consider this:

program main

  external sub

  call sub
end program main

subroutine sub
  use mod
  ! code here calls subroutines in mod
end subroutine sub

Here, you can use variables and routines from mod in sub, because sub explicitly uses mod.

Another example, where sub is an internal procedure of main:

program main
  use mod

  call sub

  contains

    subroutine sub
      ! code here calls subroutines in mod
    end subroutine sub

end program main

Also in this case you can use things from mod in sub because everything from main is in scope in sub.

Finally, in this case mod is not in scope, it is similar to the original case.

program main
  use mod
  use mod2

  call sub
end program main

module mod2

  contains

    subroutine sub

      ! code here calls subroutines in mod
    end subroutine sub

end module mod2

Another issue is the undefining of module variables, when they go out of scope. Fortran 2008 solved this by making all module variables implicitly save.



来源:https://stackoverflow.com/questions/13844426/when-does-a-module-go-out-of-scope-in-fortran-90-95

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!