子程序忽略模块中的类型声明

Big*_* Al 2 fortran

我model在模块中创建了一个类型,然后声明了一个md具有该类型的变量.在模块中包含的子例程中,md忽略上面的声明,我必须再次明确声明它.

在主程序中我不需要声明类型md,use语句似乎起作用.谁能解释为什么子程序忽略了类型声明md?

这是代码.我在Linux上使用gfortran编译器.

program main
  use struc_model
  call mod_gen(md)
  do i=1, md%ndof
    write(*,*) 'row =', i
    write(*,*) 'm=', md%m(i,:)
  end do  
end

module struc_model
  type model
    integer :: ndof
    real*8, allocatable, dimension(:,:) :: m
  end type
  type (model) :: md
  contains
  subroutine mod_gen(md)
  ! for some reason have to declare type of md again
  ! declaration above is ignored
    type (model) :: md  
    md%ndof=4
    allocate(md%m(md%ndof,md%ndof))
    md%m=0.d0
    do i=1, md%ndof
      md%m(i,i)=1.d0
    end do
  end subroutine
end module
Run Code Online (Sandbox Code Playgroud)

fra*_*lus 5

这里有三个感兴趣的术语:使用关联,主机关联和参数关联.您可以通过其他资源详细了解这些内容,但我会在此处使用它们进行解释.

首先看模块.为了清楚起见,我将把变量设为整数类型.这是一个简单的程序

module mod
  implicit none
  integer i
end module mod

program prog
  use mod
  implicit none
  print *, i       ! i is use associated
end program prog
Run Code Online (Sandbox Code Playgroud)

在这里,我们并不是说i通过模块的声明已知类型,我们说这i是模块中的变量(其类型遵循该模型).

现在看一个简化的模块:

module mod
  implicit none
  integer i

contains

  subroutine sub(i)
    integer i
  end subroutine

end module mod
Run Code Online (Sandbox Code Playgroud)

那么,为什么我需要integer i在子程序中使用该声明sub?那是因为i在那个子程序中,就像它在参数列表中那样出现,是一个伪参数.伪参数需要在其范围内指定子类型的类型.在子例程i中,对虚拟参数的引用而不是模块变量:模块变量不可访问.

如果我的程序看起来像

  use mod
  call sub(i)
end program
Run Code Online (Sandbox Code Playgroud)

我正在做的是将模块变量i---已经使用关联---传递给子程序sub作为其伪参数(通过参数关联).

现在,如果我想修改模块子程序中的模块变量,我可以改为使用主机关联

module mod
  implicit none
  integer i

contains

  subroutine sub()  ! No dummy argument i, references in here are to the module's i
  end subroutine

end module mod

program prog
  use mod
  implicit none

  call sub   ! No argument for the module's own variable
end program prog
Run Code Online (Sandbox Code Playgroud)

在该模块子程序中i引用模块变量.

但我怀疑你的意思是在程序的范围内有一个变量传递给子程序.回到你的术语:

module struc_model
  type model
    integer :: ndof
    real*8, allocatable, dimension(:,:) :: m
  end type
  contains
  subroutine mod_gen(md)
    type (model) :: md  
    md%ndof=4
    allocate(md%m(md%ndof,md%ndof))
    md%m=0.d0
    do i=1, md%ndof
      md%m(i,i)=1.d0
    end do
  end subroutine
end module

program main
  use struc_model
  type (model) :: md    ! A variable within the program's scope
  call mod_gen(md)      ! Argument associated with the subroutine's dummy
  do i=1, md%ndof
    write(*,*) 'row =', i
    write(*,*) 'm=', md%m(i,:)
  end do  
end
Run Code Online (Sandbox Code Playgroud)

综上所述

module struc_model
  type model
    integer :: ndof
    real*8, allocatable, dimension(:,:) :: m
  end type
  type (model) :: md
end module
Run Code Online (Sandbox Code Playgroud)

声明一个模块变量md,并没有声明所有被调用md的变量都是type(model).