定义前使用的 Fortran 派生数据类型

Fortran derived datatype used before defined

如何使用 use module, ONLY: 语句在模块之间包含派生数据类型(类型,而不是变量)?

更多描述:在我的 module1 中,我定义了一个派生数据类型(我们称之为 my_datatype)和该数据类型的一些数据(我们称之为 my_data)。在我的 module2 中,我需要使用 my_data。由于我的 module1 包含许多 module2 不需要的过程,我想使用 ONLY 语句只包含 my_data。但是,如果不包括数据类型,它将给我错误:

Derive datatype 'my_type' is used before defined at "type(my_type),intent(out)::A"

很明显,module2不识别module1中定义的my_datatype,因为我没有通过。但是在 'use module, only' 语句中包含派生类型的语法是什么?我正在使用 Fortran 2003。

  module step1
  implicit none
     type my_type
        integer::id
        integer,dimension(2)::my_data
     end type my_type

     type(my_type)::A
  end module step1

  module step2
  use step1,only:A
  implicit none
  contains
     subroutine change_A(A)            
        type(my_type),intent(inout)::A
        A%id = 1
        A%my_data(1) = 1
        A%my_data(2) = 2                    
     end subroutine change_A
  end module step2

  program test
  ! program is in a different folder
  use step1
  use step2
     implicit none
     call change_A(A)
  end program test

However, it is giving me error "derived datatype is used before it is defined". It looks like module2 does not recognize my_datatype defined in module1.

嗯,是的。当然,module2 不识别您的数据类型,因为它是在 module1 中定义的,而在您的 'use' 语句中您说您只想使用变量 my_data。只需在 'use' 语句中包含数据类型,它就会在 module2

中已知

鉴于您更新的问题,以下是如何实施其他人建议的修复:

(编辑:实施评论中的建议:

  1. 只在模块 step2 中导入模块 step1 的类型。
  2. 在主程序中只从第 1 步导入 A,从第 2 步导入 change_A。
  3. 请注意例程 "change_A" 中的伪参数 "A" 与例程定义中模块 step1 中的 "A" 无关。我改变了假人的名字来说明这一点。

)

module step1
  implicit none
  type my_type
     integer::id
     integer,dimension(2)::my_data
  end type my_type

  type(my_type)::A

end module step1

module step2
  use step1, only: my_type
  implicit none
contains
  subroutine change_A(dummy)
    type(my_type),intent(inout) :: dummy
    dummy%id = 1
    dummy%my_data(1) = 1
    dummy%my_data(2) = 2
  end subroutine change_A
end module step2

program test
  ! program is in a different folder
  use step1, only: A
  use step2, only: change_A
  implicit none

  call change_A(A)
  write(*,*) A

end program test

我已将 my_type 添加到 'use' 语句。