How to call a function in Fortran, which is defined in a separate file?

I am trying to compile some really old code (1986 and earlier). This code refers to an external function. Today, compilers are asking for much more code to make this work. And I continue to fail. Now I have created a small welcome program that demonstrates the problem.

hello.for

  PROGRAM hello
    USE func        
    PRINT *, "Hello World!"
    PRINT *, f ()    
  END PROGRAM hello

func.for

  MODULE func
    PUBLIC f
  CONTAINS
    FUNCTION f () 
        f='Hello Func'
    END FUNCTION
  END MODULE

This has not only one, but also two problems:

  • How to determine the type of return? Docs reports <type> FUNCTION <function>or FUNCTION <function> () <type>::<something>, but does not work.
  • How to make the linker find a function?

gfortran -c func.for works (if I use the default return type real) and creates a mod file, but the link doesn't work

$ gfortran  hello.for 
/tmp/ccHNzcXA.o: In function `MAIN__':
hello.for:(.text+0xa4): undefined reference to `__func_MOD_f'
collect2: error: ld returned 1 exit status

__func_MOD_fnot contained in the mod file, but in the o file is func.for__func_MOD_f.

Any idea?

thank

0
1

: f .

:

% gfortran -c func.f
func.f:5:8:

       f='Hello Func'
        1
Error: Can't convert CHARACTER(1) to REAL(4) at (1)

- f . , f character . :

character(len=30) :: f

. :

  MODULE func
  PUBLIC f
  CONTAINS
  FUNCTION f ()
  character(len=30) :: f
  f='Hello Func'
  END FUNCTION
  END MODULE

. :

gfortran  hello.for  

, . , :

gfortran hello.for func.o

,

gfortran -o hworld func.for hello.for

:

gfortran -c func.for
gfortran -c hello.for
gfortran -o hworld hello.o func.o

:

% ./hworld 
 Hello World!
 Hello Func   

, implicit none, . :.

module func
  implicit none
contains
function f 
  implicit none
  character(len=30) :: f
  f='Hello Func'
end function f
end module func

program hello
  use func
  implicit none        
  print *, "Hello World!"
  print *, f ()    
end program hello
+2

All Articles