Ubuntu Fortran开发环境如何搭建
小樊
45
2025-11-30 15:13:50
Ubuntu Fortran开发环境搭建指南
一 安装编译器与基础工具
- 更新索引并安装 GNU Fortran(gfortran) 与常用构建工具:
- 命令:sudo apt update && sudo apt install -y gfortran build-essential
- 验证安装:
- 命令:gfortran --version(应输出版本号,如 GNU Fortran 11/12/13)
- 说明:gfortran 支持现代 Fortran 90/95/2003/2008/2018 特性,足以覆盖大多数开发场景。
二 多版本管理与切换
- 安装特定版本(示例为 gfortran-7):
- 命令:sudo apt install -y gfortran-7
- 使用 update-alternatives 配置默认版本与切换:
- 注册版本:sudo update-alternatives --install /usr/bin/gfortran gfortran /usr/bin/gfortran-7 70
- 交互选择:sudo update-alternatives --config gfortran(按提示选择默认 gfortran)
- 验证:gfortran --version(确认已切换到目标版本)。
三 构建工具与常用数值库
- 项目构建与依赖管理:
- 安装 Fortran Package Manager(fpm)(示例为 v0.9.0,请按最新版调整下载链接与文件名):
- 下载:wget https://github.com/fortran-lang/fpm/releases/download/v0.9.0/fpm-0.9.0-linux-x86_64
- 安装:chmod +x fpm-0.9.0-linux-x86_64 && sudo mv fpm-0.9.0-linux-x86_64 /usr/local/bin/fpm
- 快速测试:
- fpm new demo && cd demo && fpm run(应成功构建并运行示例)
- 常用数值库(按需安装):
- 命令:sudo apt install -y libblas-dev liblapack-dev
- 用途:线性代数(BLAS/LAPACK)在科学计算中广泛使用。
四 编写运行与调试示例
- 经典“Hello, World”:
- 源码(hello.f90):
- program hello
implicit none
print *, ‘Hello, World!’
end program hello
- 编译与运行:
- gfortran hello.f90 -o hello && ./hello
- 使用 fpm 管理项目:
- fpm new myproj && cd myproj
- 将源码放入 src/,执行:fpm build、fpm run、fpm test
- 调试建议:
- 基础:gfortran -g -O0 hello.f90 -o hello && gdb ./hello
- 若需更丰富调试信息,可结合 valgrind 等工具进行内存检查。
五 可选 IDE 与进阶编译器
- 编辑器与 IDE:
- Visual Studio Code:sudo snap install --classic code(安装后在扩展市场搜索并安装 Fortran 扩展)
- 其他:如 Eclipse 搭配 Fortran 插件、或轻量编辑器配合终端工作流
- 进阶编译器(按需):
- Intel oneAPI Fortran Compiler(ifx) 或经典 ifort:
- 获取方式:从 Intel 官网安装 oneAPI Base Toolkit / HPC Toolkit
- 环境配置:source /opt/intel/oneapi/setvars.sh(或相应安装路径下的脚本)
- 验证:ifx --version 或 ifort --version
- 提示:不同发行版的软件源与可用版本可能不同,安装前建议确认仓库与版本兼容性。