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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With