在 Fortran 中使用模块:对“parse_”的未定义引用

Using modules in Fortran: Undefined reference to `parse_'

我正在尝试使用 the parse routine described here to parse a string in Fortran90. When following the link in the document one can download a .zip with two f90-files,我已经这样做了。然后我编译了它们 gfortran -c precmod.f90 && gfortran -c stringmod.f90。我还添加了 use strings 到我的程序中。

尽管如此,我在编译时收到以下错误 (gfortran stringmod.o precmod.o calcs.o server.o):

calcs.o: In function `calculate_':
calcs.f90:(.text+0x174): undefined reference to `parse_'
collect2: error: ld returned exit status 1

calcs.f90 如下所示,server.o 是用 C 编写的服务器,应由 calcs 调用。

program name
use strings
use iso_c_binding, only: C_CHAR, C_NULL_CHAR, C_INT

implicit none

    ! type declaration statements
    character(255) query
    integer calc, ans, portnum, calculate

    interface
        subroutine server(portnum) bind(C, name="server")
            use iso_c_binding, only: c_int
            integer(kind=c_int), value :: portnum
        end subroutine server
    end interface

    ! executable statements
    print *, "Please provide me with a port number. Plz. <3"
    read "(1i9)", portnum
    call server(portnum)

end program name

function calculate(query)
implicit none

    character(255) query, op
    integer length, i, calculate
    integer, dimension (:,:), allocatable :: inputarray

    call parse(query, ' ', inputarray, length)

    do i=1,size(inputarray)
        print *, inputarray(i, 1)
    end do

    calculate = 5

end function calculate

我尝试将 public 添加到 stringmod.f90 的顶部。

当我们有类似的东西时

program
end program

function func()
end function

那么函数 func 是一个 外部函数 ,即使它是在与主程序相同的源代码文件中给出的。这个外部函数对主程序一无所知,而主程序对外部函数也一无所知。

缺乏知识的部分原因是,在问题示例中,子例程 parse 在主程序中具有显式接口(通过模块)这一事实与 calculate.

即函数calculate有自己的作用域,没有宿主。要访问模块过程 parse,它本身可以使用模块 strings:

function calculate(query)
  use strings, only : parse
  implicit none
end function

有一个提示表明没有意识到 parsestrings 中的一个模块过程。 parse_ 中的名称修饰(单个尾部下划线)是破坏外部过程的常用方法。模块过程(没有 bind(c))通常有更详细的符号名称。

最后,我将重复评论中的内容。前面我说过主程序对外部函数知之甚少。在主程序中我们有声明

integer ... calculate

表示外部函数 calculate(具有隐式接口)具有 return 类型的整数。在这种情况下,函数可以改为内部函数

program
  use strings, only : parse
 contains
  integer function calculate
  end function
end program

而且函数 calculate 不仅有一个明确的接口(也消除了在主程序中对 return 声明的需要)而且它还可以访问 parse 通过主机协会。