mkn*_*ght 3 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
Run Code Online (Sandbox Code Playgroud)
会打印“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
Run Code Online (Sandbox Code Playgroud)
在此范例中,您可以在模块内以及use该模块中您想要访问它们的任何地方指定“全局”变量。
如果您只是使用它来声明内容(参数),您可以将其简化为:
module globals
implicit none
integer, parameter :: x=1
end module globals
program main
use globals
implicit none
print *,x
end program main
Run Code Online (Sandbox Code Playgroud)
实现此目的的旧方法涉及common块和includeing 文件,这些文件在每个访问它们的过程中声明它们。如果您发现有关块方法的教程,common我建议您忽略它们并避免在新代码中使用它们。