Search code examples
fortran

Can I pass a variable of a type defined in my current module down to another module without having to redefine the same type?


I am defining a type in my module as following:

use my_other_module

type :: myType
  integer :: &
    a, b, c
end type myType

type(myType) :: myVariable
myVariable%a=1
myVariable%b=2
myVariable%c=3

my_other_module_function(myVariable)

With this structure, the compiler requires me to define myType in both my main and my other module. I can't import my main module in my other module because that would cause a circular import. How can I structure my program to solve this problem?


Solution

  • The derived type must be defined in the root module, and any other piece of code using it needs to reference it via the use statement.

    In your case:

    module my_other_module
      implicit none
      private
    
      public :: myType
      public :: my_other_module_function
    
      type :: myType
         integer :: &
           a, b, c
       end type myType
    
      contains
    
      subroutine my_other_module_function(myVariable)
        type(myType) :: myVariable
        print *, 'do something'
      end subroutine my_other_module_function
    end module my_other_module
    
    program test
      use my_other_module, only: my_other_module_function,myType
      type(myType) :: v
    
      v = myType(1,2,3)
    
      call my_other_module_function(v)
    
    end program test
    

    Note that you should avoid circular dependencies when calling modules, otherwise the dependency tree cannot be resolved. In other words, you cannot have this:

    module m1
      use m2
    end module
    
    module m2
      use m1
    end module