fortran - 在单独的文件中构造 Fortran 派生类型

标签 fortran

我有以下程序。

program main

type mytype
  integer :: a
  integer :: b
end type

type(mytype), dimension(10,10) :: data
common data

... rest of source code ...

end program

我想将类型 mytype 定义移动到单独的文件中,但该类型将在所有子例程中使用。如何才能做到这一点?我必须将类型定义放在一起吗?

对于定义为通用的数据数组,是否可以将其定义放在单独的文件中?

目标是这样的(在 C 语言中),即将文件中的所有全局数据和 header 中的所有类型定义分组。

ma​​in.c

#include <customtypes.h>
#include <global.h>


main() {
    ...
}

global.c

#include <customtypes.h>

struct mytype data[10][10]; 

customtypes.h:

struct myType {
  int a;
  int b;
};

global.h:

extern struct mytype data[10][10];

最佳答案

模块是旨在以所需方式使用的程序单元。事实上,Fortran 标准将它们描述为 (F2018, 14.2.1):

A module contains declarations, specifications, and definitions. Public identifiers of module entities are accessible to other program units by use association

模块看起来像:

module module_name
  implicit none
  ! type, interface and object definitions
contains
  ! module procedure definitions
end module module_name

除了这个基本结构之外,模块还有更多内容(隐式无当然只是可选的),但是一本好的引用书/其他问题将填补这个细节。

让我们看一个适合问题目标的模块:

module mymodule

  implicit none

  type mytype
    integer :: a
    integer :: b
  end type

  type(mytype), dimension(10,10) :: data
end module mymodule

在其他地方,可以通过使用模块来访问定义和对象:

program main
  use mymodule  ! make all public entities from the module available

! The entity "data" is available from the module, as is the
! default structure constructor
  data(1,1) = mytype(1,1)
end program

subroutine externalsub
  use mymodule
  implicit none
  print *, data(1,1)  ! We're talking about the same element of the module's array
end subroutine

关于fortran - 在单独的文件中构造 Fortran 派生类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57837484/

相关文章:

Fortran 数组元素在内存中的顺序

linux - Rscript 会改变 LD_LIBRARY_PATH 吗?

c - 将 c 数组作为可变大小的矩阵传递给 fortran

fortran - 当我使用自动重新分配时,派生类型的可分配组件会发生什么情况?

fortran - Fortran 2003 中类型和类的区别

c++ - Fortran 中 REAL(KIND=real_normal) 的 C 等效类型是什么?

python - 使用 f2py 将对象数组传递给 Fortran

module - Fortran 中模块使用的模块的变量范围

io - Fortran:如何从文件读取数组

interface - 如何在 Fortran 界面中使用用户定义类型