How to define a variable in both subroutine and main program?

If a factor named A changing with another factor named B and factor A is defined in a subroutine and factor B is varying with input, which is defined in main program. Is it required to define the factor B in the subroutine of A in FORTRAN program ?

Could you post a short code that shows what you are trying to do but is not working? In general you can pass data to a subroutine as arguments (generally preferred) or through host association, as the following program demonstrates:

program main
implicit none
integer :: i, j
i = 3
j = 4
call print_sum_1(j) ! 7
call print_sum_2(i,j) ! 7
contains
subroutine print_sum_1(j) 
! uses host association for i
integer, intent(in) :: j
print*,i+j
end subroutine print_sum_1
!
subroutine print_sum_2(i,j)
! all data passed as arguments
integer, intent(in) :: i,j
print*,i+j
end subroutine print_sum_2
end program main
1 Like

You can also put the variable you want to be common to both routines in a module and USE the module in both the main program and the subroutine. This is a form of host association and requires you to compile the module prior to compiling both the main program and the subroutine (or you can put the subroutine in the module in which case it will have access to the variable automatically). There are also COMMON blocks but you should avoid them at all costs. The advantage of the modules is you can also rename the variable in the subroutine (if compiled separately if you want).

module mod
   use iso_c_binding, only: sp=>REAL32
   real(sp), save :: b ! save is no longer needed in most recent compilers
contains
    subroutine sub2 (a)
        real(sp), intent(in) :: a
        b = a ! b is global to sub2 and all routines that USE mod
    end subroutine sub2
end module mod

program main
   use mod
   real(sp) :: a
   a = 1.0_sp
   call sub1(a)
   print *,' b after sub1 = ', b
   a = 2.0_sp
   call sub2(a)
   print *,' b after sub2 = ',b
   stop
end program main

subroutine sub1(a)
   use mod, only: sp, c=>b ! rename b to local name c
   real(sp), intent(in) :: a
   real(sp) :: b ! this b is now local to sub1
   c=a
   b = 0.0_sp ! doesnt change b in module mod
end subroutine sub1