Variables Fortran(f90)中不同程序中变量之间的链接
我正试图适当地构造我的Fortran程序。我有一个生成网格的程序GridGeneration.f90。我想在主程序中控制网格的大小,即网格大小参数N_x和N_y。举个例子,这行得通吗Variables Fortran(f90)中不同程序中变量之间的链接,variables,definition,fortran90,Variables,Definition,Fortran90,我正试图适当地构造我的Fortran程序。我有一个生成网格的程序GridGeneration.f90。我想在主程序中控制网格的大小,即网格大小参数N_x和N_y。举个例子,这行得通吗 module MySubsAndParameters implicit none integer :: N_x, N_y include 'GridGeneration.f90' code end module MySubsAndParameters program main use MySubsAndP
module MySubsAndParameters
implicit none
integer :: N_x, N_y
include 'GridGeneration.f90'
code
end module MySubsAndParameters
program main
use MySubsAndParameters
N_x = 100
N_y = 50
code
end program main
如何在GridGeneration.f90中定义N_x和N_y才能实现这一点
此外,GridGeneration.f90中定义的变量现在是否也在我的模块和主程序中定义和分配?例如,如果GridGeneration.f90中定义了一个实x,我可以在我的主程序中使用它吗?您的问题有些不清楚,但可能有以下帮助: 至于模块变量:每个模块变量都可以由该模块中的所有子例程访问,如果没有明确定义
private
,也可以从主程序访问。因此,如果在主程序中给它们一些值,模块中的子例程就会知道这一点。反之亦然,如果您在某些模块过程中分配它们,主程序将能够使用它们
但是,如果您在主程序和子例程之间通过子例程参数(而不是模块变量)交换网格点和网格的数量,这是可能的(在我的观点中更清楚)。考虑下面的(我假设你的网格坐标是整数):
- 通过将网格大小显式地传递给例程,您不会忘记在调用例程之前从外部初始化一些模块变量。此外,很明显,例程需要哪些变量来创建网格
- 实际上,您甚至可以将网格大小传递给子例程,因为它可以根据所分配数组的大小猜测网格大小:
subroutine gengrid(grid) integer, intent(out) :: grid(:,:) integer :: nx, ny nx = size(grid, dim=1) ny = size(grid, dim=2) ! create grid based on nx and ny end subroutine gengrid
- 另一方面,如果您有支持Fortran 2003的编译器,则可以将
作为grid
数组传递给allocatable
例程,并在例程内部进行分配。虽然这在Fortran 90中是不可能的,但我所知道的所有Fortran编译器都将可分配数组作为子例程参数来实现gengrid
subroutine gengrid(grid)
integer, intent(out) :: grid(:,:)
integer :: nx, ny
nx = size(grid, dim=1)
ny = size(grid, dim=2)
! create grid based on nx and ny
end subroutine gengrid