I've made a small library which I archived. I am trying to use that archive when compiling my programs, but I end up with an undefined reference state.
Here is an example.
main.f90:
program main
use mymod, only : f
implicit none
real :: a, b
a = 5
call f(a, b)
print *, b
end program main
mymod.f90
module mymod
implicit none
private
public :: f
contains
subroutine f(a, b)
real, intent(in) :: a
real, intent(out) :: b
b = sqrt(a)
end subroutine f
end module mymod
Creation of the archive:
$ gfortran -c mymod.f90
$ ar crv libmymod.a mymod.o
a - mymod.o
Attempted compilation of main.f90:
$ gfortran -c main.f90
$ gfortran -L. -lmymod main.o
/usr/bin/ld: main.o: in function `MAIN__':
main.f90:(.text+0x27): undefined reference to `__mymod_MOD_f'
collect2: error: ld returned 1 exit status
Is this an issue with the archive, the compilation (and/or linking) of main.f90, and/or something else?
The linker does a single pass and works on the arguments from left to right. If the line reads
The linker looks at mymod first, sees there is nothing to resolve and then moves on to main.o. When it gets to main.o, it needs mymod so it looks for the next parameter and not finding any, returns an error. If the link line is changed to
that will resolve the issue. With libraries, the linker only takes what it needs. Depending on how the archive has been built, it is not unheard of to have the same library several times. Something like