学习 Fortran 面向对象编程方法
参考 Fortran 官方站点 及 B站左老师的视频 20210607-现代Fortran编程:拥抱开源Fortran环境,高效使用现代Fortran-
Fortran 语言
- Fortran 66/77
- Fixed-Form
- go to
- do … continue
- Fortran 90
- Free-Form
- module
- interface
- Fortran 95
- Fortran 03
- OOP
- class
- Fortran 08
- coarray
- submodule
- interface to C
- newunit
- Fortran 18
- interface to C
- Fortran 23
style
采用一致的风格可以提高代码的可读性,以下风格源于 Fortran stdlib
- 使用 Modern Fortran 标准
- 不要使用过时或删除的语言特征,例如
common, pause, entry, goto - 不要使用非标准语法或供应商提供的
intrinsic procedures, 如real*8, etime()
- 不要使用过时或删除的语言特征,例如
- 文件命名协议
- 每个文件只包含一个
program, module, submodule - 文件名与
program, module, submodule匹配 - 如果接口或实现分割成了
submodule,文件名应添加后缀_implementation - 测试应该添加到
test路径下并且文件名前添加test_前缀
- 每个文件只包含一个
- 缩进和空格
- 缩进 4 个空格
- 每行长度限制在 80 个字符并且不超过 132 个
- 不使用
tab字符进行缩进 - 移除行末的空格
- 变量和程序命名
- 变量、程序和关键字均采用小写
- 优先使用蛇形命名法
snake_case而非驼峰命名法CamelCase - 恰当的缩写可以忽略下划线,例如
lin_space
- 属性
- 始终为形参指定
intent属性 - 不要使用
Dimension声明数组,因为过于冗长,使用real, allocatable :: a(:), b(:,:) optional属性放在intent属性后面
- 始终为形参指定
- 块命名
- 在
end块时连接procedure, module, program名,除非程序在25行以内
- 在
其他参考风格
- 注释风格 (https://fortran-lang.org/packages/programming/)
- Best practices (https://fortran-lang.org/learn/best_practices/)
编译
- makefile
- cmake
- fpm (https://github.com/fortran-lang/fpm)
- xmake
代码要求
- 代码整洁度,复用性
- 资源调用
- 具备传参功能
- 离散计算功能: 多exe,多dll
- 有能力解析配置文件: xml yaml json toml
- 具备日志: stdlib_logger
- 使用数据存储器: hdf5 netcdf
- 数据结构: 数组 链表 二叉树
- 面向对象,简化代码架构
开发思路
- 测试代码
- 语法 => 逻辑 => 业务 => 集成 => 测试
- 开发效率
- 科学计算主要时间花费在计算上,多态接口代价相对较小
- IO效率
- IO堵塞
- 编译效率
- 使用动态库、静态库
语法
- program
- implicit none
- subroutine
- intent
- function
- pure, elemental
- interface
- to C
- to lib or dll
- polymorphic
- Overloading Operator
- module
- container
- submodule
编程范式
Fortran三种编程范式:结构化、函数式、面向对象编程
Modern Fortran的23种设计模式–面向对象编程与模板示例
- 结构化编程 Structural Programming
- 函数式编程 Functional Programming
- 面向对象编程 Object-Oriented Programming