1

I am trying to get familiarize with modules in fortran and for that I have created a simple code with module. The source code is attached.

MAIN PROGRAM

program main_prog
  use mod_f_g_h
  !
  implicit none
  ! f,g,h,s are defined in mod_f_g_h
  real :: x,y
  !
  ! read x,y
  print *, "enter x and y "
  read*, x, y
  !
  ! check
  if( y == 0 ) then
    print*, "y must be non-zero"
    stop
  end if
  !
  ! print on screen
  print*, '  x   = ', x
  print*, '  y   = ', y
  print*, 'x + y = ', f(x,y)
  print*, 'x * y = ', g(x,y)
  print*, 'x * x = ', s(x)
  print*, 'y * y = ', s(y)
  print*, 'x / y = ', h(x,y)

end program main_prog

MODULE

module mod_f_g_h
  !
  ! use other modules
  implicit none
  !
contains
  !
  real function s(x)
    implicit none
    real :: x,g
    s = g(x,x)
  end function s
  !
  real function f(x,y)
    implicit none
    real :: x,y
    f = x+y
  end function f
  !
  real function g(x,y)
    implicit none
    real :: x,y
    g = x*y
  end function g
  !
  real function h(x,y)
    implicit none
    real :: x,y
    h = x/y
  end function h
end module mod_f_g_h

But when I try to compile and link the code, using

gfortran -c mod_f_g_h.f90
gfortran -c main.f90
gfortran *.o -o run.x

Got the following error (in last step)

mod_f_g_h.o: In function `__mod_f_g_h_MOD_s':
mod_f_g_h.f90:(.text+0xb6): undefined reference to `g_'
collect2: ld returned 1 exit status

I think, I have defined all the variables, moreover I am not linking any external library, so I don't know why this error is appearing? Any comment/idea?

  • I indented your code to make it more readable. You definitely don't repeat implicit none everywhere. Once per module is enough. Also, the exclamation marks in empty lines do more harm than good to readability. – Vladimir F Героям слава Jun 02 '14 at 13:15
  • I'm just a beginner so not very familiar with good programming practices, thanks for pointing out –  Jun 02 '14 at 14:40

1 Answers1

3

It should read

real function s(x)
implicit none
real :: x
s = g(x,x)
end function s

inside the module.

Further explanation by VladimirF:

By real g you were declaring the function g inside s as an external real function distinct from that one in the module.

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68