Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linking fortran module: "undefined reference"

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?

like image 968
Christopher White Avatar asked Jul 16 '12 21:07

Christopher White


1 Answers

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.

like image 131
M. S. B. Avatar answered Sep 22 '22 22:09

M. S. B.