Linking fortran module: "undefined reference"

10,041

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.

Share:
10,041
Christopher White
Author by

Christopher White

Updated on June 12, 2022

Comments

  • Christopher White
    Christopher White almost 2 years

    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?