Inter-submodule procedure calling

A parent module and its submodules are in their own files as shown below. Can submodule B call procedure defined in submodule A through use association?

(File) module parent
|
|—(File) submodule A
| public module procedure childA
|
|—(File) submodule B
use submodule A ? or use parent:submodule A
call childA

1 Like

They can call each other with two changes:

  1. Interfaces for the child procedures must be defined in the parent module
  2. There is no need for use, because all children belong to the same parent module

Here’s a complete example:

main.f90:

module parent
	implicit none
	interface
		module subroutine subroutine_a()
		end subroutine subroutine_a
		module subroutine subroutine_b()
		end subroutine subroutine_b
	end interface
end module parent

program main
	use parent
	implicit none
	call subroutine_b()
end program main

a.f90:

submodule(parent) a
	implicit none
	contains
		module subroutine subroutine_a
			print *, "hello from subroutine_a"
		end subroutine subroutine_a
end submodule a

b.f90:

submodule(parent) b
	implicit none
	contains
		module subroutine subroutine_b
			print *, "hello from subroutine_b"
			call subroutine_a()
		end subroutine subroutine_b
end submodule b

If procedure childA is in parent module, it will be visible to all submodules, which is not desirable.

Fortran’s submodule siblings are unaware of each other’s existence. But you can extend the submodule hierarchy as much as you want:

module mod1
    implicit none
    ...
end module mod1

submodule (mod1) sm_impl1
    implicit none
    interface
        module subroutine sub1() ! visible to descendants of sm_impl1 but not to mod1
        end subroutine
    end interface
end submodule sm_impl1

submodule (mod1:sm_impl1) sm_impl2
    implicit none
contains
    subroutine do_something()
        call sub1()
    end subroutine
end submodule sm_impl2

submodule (mod1:sm_impl1) sm_impl3
    implicit none
contains
    subroutine do_something()
        call sub1()
    end subroutine
end submodule sm_impl3

Notice that do_something is defined in both sm_impl2 and sm_impl3, since they’re siblings and are therefore unaware of what the other submodule declares.

1 Like