3

My intended use is

program main
  use mod

  external sub

  call sub
end program main

subroutine sub
  ! code here calls subroutines in mod
end subroutine sub

Specifically, will module mod be in scope in subroutine sub? Also, I'd be interested to know more generally when a module is in/out of scope. I'm using gfortran 4.6.1, if it matters.

astay13
  • 6,857
  • 10
  • 41
  • 56

1 Answers1

4

It is not in scope of subroutine sub, as sub cannot call routines or use variables from mod, because sub is not part of the program main. They have nothing in common, are separate compilation units and only may call each other (if they are callable).

Consider this:

program main

  external sub

  call sub
end program main

subroutine sub
  use mod
  ! code here calls subroutines in mod
end subroutine sub

Here, you can use variables and routines from mod in sub, because sub explicitly uses mod.

Another example, where sub is an internal procedure of main:

program main
  use mod

  call sub

  contains

    subroutine sub
      ! code here calls subroutines in mod
    end subroutine sub

end program main

Also in this case you can use things from mod in sub because everything from main is in scope in sub.

Finally, in this case mod is not in scope, it is similar to the original case.

program main
  use mod
  use mod2

  call sub
end program main

module mod2

  contains

    subroutine sub

      ! code here calls subroutines in mod
    end subroutine sub

end module mod2

Another issue is the undefining of module variables, when they go out of scope. Fortran 2008 solved this by making all module variables implicitly save.

  • That's helpful, thanks. So in general, a module is in scope inside a program unit that "uses" it, but not in external units called by the main unit? – astay13 Dec 12 '12 at 18:22
  • What about the case where you have `sub1` defined in `mod1` and you have a subroutine `sub2` which accepts an external routine as an argument. Could you pass `sub1` to `sub2`? `call sub1(sub2)` ? *it works with `gfortran` ... – mgilson Dec 12 '12 at 19:10
  • Your second example (with the internal procedure) fails to compile with gfortran (and it should fail with other compilers too I'd think). You can't declare a procedure as external and then provide an internal procedure of the same name. – mgilson Dec 12 '12 at 19:17
  • The extra external definition is just a copy-paste error of course, thanks for notice. It can be deleted everywhere btw., a subroutine does not have to be explicitly declared as external. – Vladimir F Героям слава Dec 12 '12 at 21:05
  • Fr the first comment: I think it should work. I don't see any reason why not, but I did not study the standard for that. – Vladimir F Героям слава Dec 12 '12 at 21:08