0

For some use I need to define a function inside another function inside a fortran module. A sample code for easy comprehension is

module func
implicit none
contains

real function f(x,y)
real x,y,g

real function g(r)
real r
g=r
end function g

f=x*g(y)
end function f
end module func

use func
implicit none

write(*,*) f(1.0,1.0)
end

This is giving lots of errors in gfortran like unexpected data declaration, expected end function f, not g....etc.

What is the correct way of defining a function inside another function in fortran?

1
  • 1
    You can make g an internal function of f. Or, given the simplicity of your example, you could use a statement function. The former is preferred and the latter is obsolescent. Commented Apr 2, 2020 at 15:39

1 Answer 1

3

You use an internal subprogram, see below. Note internal subprograms themselves can not contain internal subprograms.

ian@eris:~/work/stack$ cat contained.f90
Module func

  Implicit None

Contains

  Real Function f(x,y)

    ! Interface explicit so don't need to declare g
    Real x,y

    f=x*g(y)

  Contains

    Real Function g(r)
      Real r
      g=r
    End Function g

  End Function f

End Module func

Program testit

  Use func

  Implicit None

  Write(*,*) f(1.0,1.0)

End Program testit
ian@eris:~/work/stack$ gfortran-8 -std=f2008 -Wall -Wextra -fcheck=all -O -g contained.f90 
ian@eris:~/work/stack$ ./a.out
   1.00000000    
ian@eris:~/work/stack$ 
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any such thing that an internal subprogram cannot call an external function? In my original code, when I am trying to use an external function inside the subprogram section, as you said in the answer, defined in another module, gfortran is saying undefined reference... Is there any such thing?
Need to actually see the error message and what you did. But, from the descirption you either forgot to link a library or an object file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.