Nested functions: Error: CONTAINS statement at (1) is already in a contained program unit

Nested functions: Error: CONTAINS statement at (1) is already in a contained program unit

我编写了一个模块来计算给定函数 f(x) 的积分。现在我想在 Fortran 主程序中计算函数乘积的积分。

主要程序是:

program exercici3
!Let's import the gquad function from legendre for integrals
use legendre

implicit none

contains

subroutine comp_average_dist(psi)
    !Compute the integral of psi(x)*x*psi(x)
    real(8) :: x_bar
    interface
        function psi(x) result(f)
            real(8) :: x,f
        end function
    end interface

    x_bar = gquad(sandwich_dist,1000,0,1d30)

    contains

    function sandwich_dist(x) result(sand)
        real(8) :: x,sand
          sand = psi(x)*x*psi(x)
    end function sandwich_dist
end subroutine
end program

我遇到的问题是当我用 gfortran 4.8.4 编译我的程序时它引发了下一个错误:

Error: CONTAINS statement at (1) is already in a contained program unit

我正在寻找在 Fortran 中放置嵌套函数的方法 here。你看到错误了吗?

你所说的 "nested functions" 是,就 Fortran 语言而言,内部子程序

您 link 的文档关于此类包含的函数在很大程度上是正确的,但是忽略了一个重要的方面和错误的来源:内部过程本身可能不包含另一个内部过程。

对于问题中的例子,comp_average_dist是主程序的一个内部子程序。 sandwich_dist 是试图创建该子例程的内部函数,编译器正确地抱怨。

正如您在评论中指出的那样,如果 comp_average_dist 是一个模块过程,则允许它具有内部函数。 sandwich_dist 将有权访问主机子例程和模块。