Linking fortran module: “undefined reference”

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-06 03:22:18

问题


I'm trying to write some functions/subroutines in a module that call another function in the same module and running into linker errors. A toy example displaying the same behavior:

!in test.f

module m1
  implicit none
contains
  real function mult(a, b)
    real :: a
    real :: b
    mult = a * b
    return
  end function mult

  real function sq(a)
    real :: a, mult
    sq = mult(a, a)
    return
  end function sq

end module m1

program main
use m1
write(*,*) sq(2.0)
end program

When I try to compile this, I run into trouble:

[christopher@archlinux metropolis]$ gfortran -ffree-form test.f
/tmp/ccpzdTLE.o: In function `__m1_MOD_sq':
test.f:(.text+0x20): undefined reference to `mult_'
collect2: error: ld returned 1 exit status

On the other hand, compiling only (gfortran -c -ffree-form test.f -Wall) runs with no complaint.

Now this looks for all the world like a compiler error---in the module it comes up with a reference to mult_ when it really ought to com up with __m1_MOD_sq---but I have a very hard time believing that this is a compiler bug rather than me doing something stupid.

DDG didn't turn up anything useful. Most of the similar problems ocurred in splitting the module off from one main file. In those cases, things worked when the module was in the same file as the program, which is not the case here. I looked at a number of pages on modules in Fortran and didn't see anything relevant.

Can anyone point me to appropriate documentation or, better yet, explain what's going on and how I can fix it?


回答1:


You don't need to declare function mult in function sq, i.e., there is no need for "real :: mult". sq already "knows" about mult since it is in the same module. The interface of mult is known to sq since they are in the same module. The interface of mult and sq are known to the main program since it uses the module. Having both the module providing the interface and the declaration is confusing the compiler.



来源:https://stackoverflow.com/questions/11512897/linking-fortran-module-undefined-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!