Pass a common variable to a subroutine in Fortran

2.3k views Asked by At

I'm customizing a commercial code which deeply uses common block to define global variables.

What I would like to do is to pass only one of those variable to a subroutine, but not making the include, because I don't need the other several variables defined as common.

The only way I found to do this has been to previously define a new local variable, assign to it the value of the global variable, and then pass the new variable to the subroutine, but I don't like that way of proceed..

Is there a solution to tell Fortran to convert a variable to local when passing it to a subroutine?

Here one example:

Main program:

INTEGER :: A
REAL :: Y(20)
COMMON /VARS/ Y, A
INTEGER :: res, transfer_var
transfer_var = A
call sub_test(transfer_var, res)
...

Subroutine:

subroutine sub_test(var1, var2)
INTEGER, intent(in) :: var1
INTEGER, intent(out) :: var2
var2 = 1 + var1
return
end
1

There are 1 answers

0
agentp On

This is a minimal working example of code that does not exhibit the behavior you describe. A is assigned in main, passed by common to sub_one, then used directly as a subroutine argument.

 implicit none
 INTEGER :: A,res
 COMMON /VARS/ A
 A=41
 call sub_one()
 end 

 subroutine sub_one()
 INTEGER :: A,res
 COMMON /VARS/ A
 call sub_test(a,res)
 write(*,*)res
 end

 subroutine sub_test(var1, var2)
 INTEGER, intent(in) :: var1
 INTEGER, intent(out) :: var2
 var2 = 1 + var1
 return
 end

this compiles without issue and returns the result 42.

Can you provide example code that shows the issue?