Fortran中模块使用的模块的变量范围 [英] Scope of variables in case of modules used by modules in Fortran

查看:439
本文介绍了Fortran中模块使用的模块的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到父模块使用的(子)模块中的变量只能通过父模块在主程序中访问。这是一个在C / C ++中明确区分Fortran中 include 语句的概念。以下程序清楚地说明了这一概念。

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 clearly distinguishes use statement in Fortran from include statement in C/C++. The following programs clearly illustrate this concept.

a.f90

module a_mod
 use b_mod
 implicit none

 integer :: a
end module

b.f90

module b_mod
  use c_mod
  implicit none

  integer :: b

end module

c.f90

module c_mod
  implicit none

  integer :: c = 10

contains

  subroutine inc_c
    c = c + 10
  end subroutine inc_c
end module

test.f90

program test
  use a_mod
  implicit none

  call inc_c
  write(*,*),c
end program

注意我能够通过使用 a_mod 调用 c_mod 中的函数。请注意,我无法直接观察到 c_mod 是可用的,除非我遍历依赖列表。

Note that I am able to call a function in c_mod by just using a_mod. Note that I cannot directly observe that c_mod is available unless I traverse the dependency list.

但是在一个复杂的软件中,如果变量可用于特定行,是否有一种简单的方法可以知道(例如,使用IDE)?

But in a complicated software, is there a simple way to know (say, using an IDE) if a variable is available for use at a particular line?

推荐答案

<在我看来,最好的办法是避免使用毯子使用语句,特别是对于大型且有时笨重的模块。而是通过 only 关键字指定要继承的模块实体,例如:

The best thing to do, in my opinion, is to avoid the use of blanket use statements, especially for large and sometimes unwieldy modules. Instead, specify which module entities to inherit via the only keyword, such as:

program main
   use a_mod, only : c, inc_c
   implicit none

   call inc_c
   write(*,*) c
end program main

这有效,但令人困惑,因为 a_mod 不是 c inc_c 的真正所有者。因此,您应该尝试使用实际声明它们的实体

This works, but it's confusing because a_mod isn't the real owner of c and inc_c. Therefore, you should try to use entities from where they are actually declared, which gives:

program main
   use c_mod, only : c, inc_c
   !   ^ This has changed
   implicit none

   call inc_c
   write(*,*) c
end program main

现在,任何阅读代码的人都清楚地知道哪些变量和子程序在范围内以及它们来自何处。

Now, anybody reading the code has a clear notion of which variables and subroutines are in scope and where they come from.

最后,这还有一个额外的好处,即降低使用 c 的风险,而不会意识到它实际上来自于 c_mod 。当不使用隐式无时,这尤其是一个问题!

Finally, this has the added benefit of reducing the risk that you use c without realizing it's actually inhereted from c_mod. This is particularly a problem when not using implicit none!

这篇关于Fortran中模块使用的模块的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆