Ubuntu 下 Fortran 模块使用指南
一 环境准备与编译要点
sudo apt update && sudo apt install gfortran build-essential二 最小示例 定义与使用模块
module m_math
implicit none
contains
function add(a, b) result(r)
real, intent(in) :: a, b
real :: r
r = a + b
end function add
end module m_math
program main
use m_math, only: add ! 引入模块中的 add
implicit none
real :: x, y, z
x = 1.0
y = 2.0
z = add(x, y)
print *, 'add = ', z
end program main
# 1) 编译模块
gfortran -c m_math.f90 -o m_math.o
# 2) 编译主程序(当前目录已生成 m_math.mod,无需额外 -I)
gfortran -c main.f90 -o main.o
# 3) 链接生成可执行文件
gfortran main.o m_math.o -o main.exe
# 4) 运行
./main.exe
use m_math 必须在 implicit none 之后(或同一位置之后),这是 Fortran 的语法约束。三 使用外部库的模块 以 NetCDF 为例
sudo apt update
sudo apt install libnetcdf-dev libnetcdff-dev
nc-config --version # 查看 NetCDF-C 版本
nf-config --version # 查看 NetCDF-Fortran 版本
program test_nc
use netcdf ! 使用 NetCDF Fortran 模块
implicit none
print *, 'NetCDF-Fortran version: ', nf90_inq_libvers()
end program test_nc
# 方式一:使用 nf-config 自动参数
gfortran test_nc.f90 `nf-config --fflags --flibs` -o test_nc.exe
# 方式二:手动指定包含路径与库(路径因系统而异)
gfortran test_nc.f90 -I/usr/include -L/usr/lib -lnetcdff -lnetcdf -o test_nc.exe
./test_nc.exe
use netcdf 会触发对 netcdf.mod 的查找;若 .mod 不在默认搜索路径,需用 -I 指定其所在目录。四 工程组织与构建工具
project/
├─ modules/
│ └─ m_*.f90
├─ prog/
│ └─ main.f90
└─ build/
# 编译模块
gfortran -c modules/m_math.f90 -o build/m_math.o
# 编译主程序(指定模块目录)
gfortran -c prog/main.f90 -I modules -o build/main.o
# 链接
gfortran build/main.o build/m_math.o -o build/main.exe
fpm build、fpm run 即可自动处理模块依赖与编译顺序,适合中小型项目与快速原型开发。