我有以下程序。
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 中的所有类型定义分组。
main.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/