Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Variables Fortran中外部声明的(全局)变量_Variables_Fortran_Global_Subroutine - Fatal编程技术网

Variables Fortran中外部声明的(全局)变量

Variables Fortran中外部声明的(全局)变量,variables,fortran,global,subroutine,Variables,Fortran,Global,Subroutine,我想知道是否有可能声明一个变量,并将声明传递给另一个子例程或程序(因此成为全局的) 比如说 program main implicit none call mysub print *, x end program main subroutine mysub implicit none integer, parameter :: x = 1 end subroutine mysub 将打印“1” 这可能吗?我之所以想这样做,是因为我正在处理的程序有大量变

我想知道是否有可能声明一个变量,并将声明传递给另一个子例程或程序(因此成为全局的)

比如说

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

subroutine mysub
    implicit none
    integer, parameter :: x = 1
end subroutine mysub
将打印“1”


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

在现代Fortran中实现这一点最直接的方法是使用模块

考虑

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
在此范例中,您指定模块内的“全局”变量,并在您希望访问它们的任何地方使用该模块

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

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

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


实现这一点的较旧方法涉及
公共
块和
包含
的文件,这些文件在访问它们的每个过程中都声明了它们。如果你找到一个关于
常用
块方法的教程,我建议你忽略它们,避免在新代码中使用它们。

可能有“全局”变量,但不是这样。如果你用一个简短的例子来解释你想做什么,也许我们可以给你一个更有用的答案;关于如何在fortran中使用模块,有许多有用的指南。