Home > Net >  How to write function of Fortran f90 in a separate file?
How to write function of Fortran f90 in a separate file?

Time:01-17

I want to write function in a separate file myfunction.f90 and how to modify test.f90 to call it

program test
    implicit none
    external myfunc
    real :: x,myfunc
    x = 5
    write(*,*) myfunc(x)
end program test


function myfunc(x)
    implicit none
    real :: myfunc,x
    myfunc = x**2
end function myfunc

I separate into 2 files test.f90

program test
    implicit none
    external myfunc
    real :: x,myfunc
    x = 5
    write(*,*) myfunc(x)
end program test

and myfunc.f90

function myfunc(x)
    implicit none
    real :: myfunc,x
    myfunc = x**2
end function myfunc

But it does not work

CodePudding user response:

The canonical solution is to create a file with a module that includes all your functions after the contains keyword.

Then reference the module in your program with use mymodule and include both files to the compiler command.

CodePudding user response:

If you wrap the function like this:

module mymod function myfunc(x) implicit none real :: myfunc,x myfunc = x**2 end function myfunc end module

the Visual Studio Code throws error

  • Related