【问题标题】:errors when transforming program into module with subroutine使用子程序将程序转换为模块时出错
【发布时间】:2019-10-03 18:41:38
【问题描述】:

给定一个运行良好的简单程序,例如:

program test
implicit none
real, allocatable :: x(:)
real :: su, si
allocate(x(3))
x(:) = (/1,2,3/)
su=sum(x(:))
si=size(x(:))
end program

我尝试将其转换为带有子程序的外部模块:

module test
implicit none
real, allocatable, intent(in) :: x(:)
real, intent(out) :: su, si
contains
subroutine sumsize(x(:),su,si)
    su=sum(x(:))
    si=size(x(:))
end subroutine
end module

但是,我无法使用几个错误消息来编译它,我相信这些错误消息大部分是基于 x(:)susi 都不是 DUMMY 变量。

假人在哪里以及如何定义?这似乎是一个简单的形式错误。

另一个错误状态是子程序头中的垃圾,并在使用subroutine sumsize(x,su,si) 定义它时消失。为什么子程序的输入不能是向量?

通过gfortran -ffree-form -c module_test.f -o test.o 使用gfortran - gcc v. 8.3.0-6 (Debian) 编译。

【问题讨论】:

    标签: module compilation fortran subroutine


    【解决方案1】:

    虚拟参数,在其他编程语言中也称为函数参数,必须在函数或子例程中声明。

    此外,参数列表(子程序名称后括号中的参数名称)不应包含任何额外的括号。

    module test
      implicit none
    
    contains
    
      subroutine sumsize(x,su,si)    
        real,  intent(in) :: x(:)
        real, intent(out) :: su, si
    
        su=sum(x(:))
        si=size(x(:))
      end subroutine
    end module
    

    此外,您通常不希望虚拟参数为 allocatable。这通常在子例程内分配或取消分配数组时使用,或者如果您希望允许使用未分配的数组。

    program test
      implicit none
    
      real, allocatable :: main_x(:)
      real :: main_su, main_si
    
      allocate(main_x(3))
      main_x(:) = (/1,2,3/)
    
      call  sumsize(main_x, main_su, main_si)
    end program
    

    我用main_前缀重命名了变量。不需要,只是为了明确它们与子程序中的名称不同。

    【讨论】:

    • 从主程序调用时数组是直接分配的吗?假人是“子程序括号中的任何内容”?
    • 在调用子程序之前,应该在主程序中分配数组。虚拟参数基本上是来自主程序或调用子程序的其他代码的实际变量的占位符。
    • 就这么简单。泰。
    猜你喜欢
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2016-06-11
    • 2019-12-21
    • 2010-12-06
    相关资源
    最近更新 更多