Reputation: 139
I've written a program in Fortran 90 that reads hundreds on inputs from a text file and performs many different, sequential operations on them.
I don't want to keep passing these hundreds of values to each subroutine (there are many!). Is there a way that I can save data I read from this file to global variables that can be accessed by any subroutine? I imagine that somehow I could save these values to a module that can be called by each subroutine, but I am unsure of how to do so.
Upvotes: 1
Views: 2738
Reputation: 21431
Orthogonal to the use of module variables, consider using one or more derived types to group together your "hundreds of values" (with values that are related in some way being grouped into a particular derived type).
(At a more basic level, sometimes representation of information in arrays rather than a series of scalars is a better fit to the nature of that information - so store and pass that information in arrays.)
This makes it a lot easier to understand the information flow in your program - at the site of a procedure reference someone reading your code will necessarily not be aware of the modules and module variables that the referenced procedure may access. In some cases it can also make it easier to extend your program in future - it is easier to have multiple extant instances of things if they are described in a derived type, rather than as a series of module variables.
So instead of:
SUBROUTINE proc( temperature, pressure, &
composition_a, composition_b, composition_c )
REAL, INTENT(IN) :: temperature, pressure, &
composition_a, composition_b, composition_c
...
Consider:
TYPE State
REAL :: temperature
REAL :: pressure
REAL :: composition(3)
END Type State
...
SUBROUTINE proc(system_state)
TYPE(State), INTENT(IN) :: system_state
...
In other cases module variables may well be more appropriate - the split is a matter of judgement.
Upvotes: 4
Reputation: 29391
You just place the variables into a module and use that module from each subroutine. Or have the subroutine in the same module. This is the preferred approach to global variables in modern Fortran; preferred over common blocks. Common blocks add the unnecessary complication of storage sequence. In principle you should include SAVE on each declaration because the values are allowed to be lost if the module goes out of scope, that is, if during the program execution neither the main program nor any subroutine is using the module. Probably no compiler actually does this.
module my_mod
real, dimension (100) :: array
integer :: OneInt
contains
subroutine X
end subroutine X
end module my_mod
program my_prog
use my_mod
read () array
call subroutine X
end program my_prog
Upvotes: 5