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

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

问题描述

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

例如,



 程序主体
隐式无
调用mysub
print *,x
end program main

子程序mysub
隐式无
整型,参数:: x = 1
结束子程序mysub

打印1



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

解决方案

在现代Fortran中执行此操作最直接的方法是使用模块。



 模块全局变量
隐式无
整数:: x
结束模块全局变量

程序主体
使用全局变量
隐式无
调用mysub
print *,x
结束程序main

子程序mysub
使用全局变量
隐式不变
x = 1
结束子程序mysub

在这个范例中,您可以在模块内指定您的全局变量,并在您希望访问的任何位置使用使用模块。



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

 模块全局变量
隐式无
整数,参数:: x = 1
终端模块全局变量

程序主变量
使用全局变量
implicit none
print *,x
end program main






使用旧方法来完成这项工作涉及 common blocks和 include ing文件宣布他们每一个访问它们的程序。如果您发现一本处理 common 块方法的教程,我建议您忽略它们并避免在新代码中使用它们。


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)

For example

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

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

Would print "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.

解决方案

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

Consider

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


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天全站免登陆