Scope of variables in case of modules used by modules in Fortran

前端 未结 3 856
名媛妹妹
名媛妹妹 2021-01-21 01:17

I\'ve noticed that variables in a (child) module, which are used by a parent modules are accessible in a main program through just the parent module. This is one concept which c

3条回答
  •  隐瞒了意图╮
    2021-01-21 01:43

    As Vladimir F suggested in a comment, you can solve this issue using private and public statements in your modules. If you rewrite your modules like this:

    module a_mod
      use :: b_mod
    
      private
      public :: a
    
      integer :: a
    end module
    
    module b_mod
      use :: c_mod
    
      private
      public :: b
    
      integer :: b
    end module
    
    module c_mod
      private
      public :: c, inc_c
    
      integer :: c = 10
    contains
      subroutine inc_c
        c = c + 10
      end subroutine
    end module
    

    In this case, the statement private in the beginning of each module means that quantities declared in the module are not exported by default. You now have to explicitly declare what variables and subroutines to make available when you use the module by adding a public statement. (This could alternatively be done in one line using the syntax integer, public :: c = 10.) This practice prevents c_mod variables from leaking out of b_mod, and so on.

提交回复
热议问题