I have a module that contains a subroutine which in turn contains a function. I say use themodule
in my main program and I can call thesubroutine
, but how do I access the function that is contained in the subroutine?
The code looks like this:
module useful
integer, parameter :: N=2
double precision, parameter :: xmin=1, xmax=10, pi=3.1415926535898
double complex :: green(N,N), solution(N), k=(2.0,0.0)
contains
subroutine y(n1)
contains
function x(n1)
real :: n1, x
x=n1*(xmax-xmin)/N
end function x
end subroutine y
end module useful
You should not contain the function inside the subroutine. Have the function after the subroutine. Just have as many procedures (subroutines & functions) in the module as you need. Start each with a subroutine or a function statement and end them with their corresponding end statement. Do not nest them inside each other ... instead, one after the other. Have only the module contains statement. Then "use" that module from your main program, or from a procedure outside of the module.
The subroutines and functions in the module are also accessible to each other. No need to use a "contains".
Some additional remarks. You can put the function inside the subroutine, if this function is used by this subroutine only. In this case nesting the functions is a useful concept.
If you want to hide some functions in the module for the external program (forever), you declare those hidden functions as private in your module.
i.e
module useful
public y,x ! shall be accessible by "use useful" statement in external program
private ! anything else declared in the module is hidden for external program
integer, parameter :: N=2
!...
contains
subroutine y(n1)
end subroutine y
function x(n1)
end function x
end module useful
using public and private helps you to avoid mistakes with contamination of your namespace by using the statements
use useful, only: y,x
use useful2, only: x,y,z
use useful3, only: x2,x3,x4
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