1

我有一个 FORTRAN 95 代码,其中在主程序中声明了这些变量:

integer :: i
real(8) :: dx                               
real(8), allocatable :: X(:), Y(:), Z(:)

以下函数在程序期间的某个时间点使用这些值:

function Funcion_ceros(var_4)           
        implicit none
        real(8), intent(in) :: var_4(2)
            real(8) :: Funcion_ceros(2)
            Funcion_ceros(1) = var_4(1) - Y(i) - dx*var_4(2)
            Funcion_ceros(2) = var_4(2) - Z(i) - dx*F(X(i + 1), var_4(1), var_4(2))
end function Funcion_ceros

如果我在主程序的 contains 部分中包含此函数,则不存在编译问题。但是,当将其分成一个模块时,它会失去对这些变量的访问权限。我也尝试在模块中指定上面编写的相同变量,并得到以下错误:

Symbol 'i' at (1) conflicts with symbol from  module 'Module_Name', use associated at (2).

如何将此函数分成一个模块,同时允许它从主程序访问它使用的变量?

4

1 回答 1

2

您也可以将变量放入模块中,然后use语句使它们也可用于主程序。

module scope_mod
    implicit none
    character(len=4) :: a = "mod "
    character(len=4) :: b = "mod "
    character(len=4) :: c = "mod "
contains
    subroutine sub()
        implicit none
        character(len=4) :: b
        a = "sub "
        b = "sub "
        write(*, *) "in sub: A from ", a, ", B from ", b, ", C from ", c
    end subroutine sub
end module scope_mod

program scope_test
    use scope_mod
    implicit none
    a = "main"
    write(*, *) "in main: A from ", a, ", B from ", b, ", C from ", c
    call sub()
    write(*, *) "after sub: A from ", a, ", B from ", b, ", C from ", c
end program scope_test

输出:

 in main: A from main, B from mod , C from mod 
 in sub: A from sub , B from sub , C from mod 
 after sub: A from sub , B from mod , C from mod 

更新:use我注意到您说您将变量“也”放在模块中 - 如果您将它们放在模块中,它们将通过语句提供给主程序。如果您随后声明另一个具有相同名称的变量,它将发生冲突。在模块中声明变量,它们对两者都可用。

于 2015-05-05T01:25:33.633 回答