Fortran 中的外部声明(全局)变量 [英] Externally declared (global) variable in Fortran

查看:36
本文介绍了Fortran 中的外部声明(全局)变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以声明一个变量并将声明转移到另一个子例程或程序(因此成为全局)

I want to know if it's possible to declare a variable and have declaration carry over to another subroutine or program (hence become global)

例如

program main
    implicit none
    call mysub
    print *, x
end program main

subroutine mysub
    implicit none
    integer, parameter :: x = 1
end subroutine mysub

将打印1"

这可能吗?我想这样做是因为我正在处理的程序有大量变量,除非必要,否则我宁愿避免复制.

Is this possible? I want to do this because a program I'm working on has large sets of variables that I would rather avoid copying unless necessary.

推荐答案

在现代 Fortran 中最直接的方法是使用模块.

The most straightforward way to do this in modern Fortran is with modules.

考虑

module globals
  implicit none
  integer :: x
end module globals

program main
  use globals
  implicit none
  call mysub
  print *,x
end program main

subroutine mysub
  use globals
  implicit none
  x = 1
end subroutine mysub

在此范例中,您可以在模块中指定全局"变量,并在您希望访问它们的任何地方使用该模块.

In this paradigm you specify your "global" variables within the module and use that module everywhere you want access to them.

如果您只是使用它来声明内容(参数),您可以将其简化为:

If you are just using this to declare contants (parameters) you can simplify this to:

module globals
  implicit none
  integer, parameter :: x=1
end module globals

program main
  use globals
  implicit none
  print *,x
end program main

<小时>

实现这一点的旧方法涉及 common 块和 includeing 文件,这些文件在每个访问它们的过程中声明它们.如果您找到处理 common 块方法的教程,我建议您忽略它们并避免在新代码中使用它们.


The older method to accomplish this involved common blocks and includeing files that declared them every procedure that accessed them. If you find a tutorial dealing with the common block method I advise you to ignore them and avoid their use in new code.

这篇关于Fortran 中的外部声明(全局)变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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