Vladimir Vargas
Vladimir Vargas

Reputation: 1824

How to call an external function?

I have the following function

REAL FUNCTION myfunction(x)

    IMPLICIT NONE
    REAL, INTENT(IN) :: x
    myfunction = SIN(x)

END FUNCTION myfunction

in a file called myfunction.f90

I want to use this function in other f90 file. How can I do this?

Upvotes: 4

Views: 11798

Answers (2)

Holmz
Holmz

Reputation: 724

Just use external...

...
REAL, EXTERNAL :: myfunction
REAL           :: X, Y
...

Y = myfunction(x)

That said, it is wiser to let the compiler do what it does and catch the obvious issues that are easy to miss... so jabirali has a good approach.

Upvotes: 1

jabirali
jabirali

Reputation: 1346

The recommended way to do this in modern Fortran would be to create a module, let's call it e.g. "mymath". In that case, you can create one file mymath.f90 containing something like this:

module mymath
contains
  function myfunction(x) result(r)
    real, intent(in) :: x
    real             :: r

    r = sin(x)
  end function
end module

Then another file main.f90 like this:

program main
  use :: mymath

  print *,myfunction(3.1416/2)
end program

Then you just compile the source files together:

gfortran mymath.f90 main.f90

The resulting executable should work as expected.

EDIT:

If you really prefer to stay away from modules, then you can make mymath.f like this:

function myfunction(x) result(r)
  real, intent(in) :: x
  real             :: r

  r = sin(x)
end function

And make main.f90 like this:

program main
  real, external :: myfunction

  print *,myfunction(3.1416/2)
end program

It compiles and works like the other solution. Note that if you choose to use external instead of module, the compiler will usually not check that the arguments you give to myfunction have the right number, types, and dimensions — which may complicate debugging in the future.

Upvotes: 9

Related Questions