在 Linux 系统中安装和使用 gfortran
(GNU Fortran 编译器)非常简单,以下是详细指南:
sudo apt update
sudo apt install gfortran -y
# CentOS/RHEL 7/8
sudo yum install gcc-gfortran -y
# Fedora
sudo dnf install gcc-gfortran -y
sudo pacman -S gcc-fortran
gfortran --version
输出示例:
GNU Fortran (Ubuntu 9.4.0-1ubuntu1~20.04) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
假设有一个 Fortran 源文件 hello.f90
:
program hello
print *, "Hello, Fortran!"
end program hello
gfortran hello.f90 -o hello # 编译生成可执行文件 hello
./hello # 运行程序
输出:
Hello, Fortran!
选项 | 说明 |
---|---|
-o output | 指定输出文件名 |
-Wall | 启用所有警告 |
-O2 | 优化级别 2(默认) |
-O3 | 更高级别的优化 |
-g | 生成调试信息(用于 gdb) |
-fcheck=all | 启用所有运行时检查 |
-ffree-form | 使用自由格式(默认) |
-ffixed-form | 使用固定格式(旧版 Fortran) |
gfortran -Wall -O2 -g hello.f90 -o hello_optimized
如果程序依赖外部库(如 BLAS、LAPACK),需指定库路径和链接选项:
gfortran my_program.f90 -o my_program -llapack -lblas -L/usr/local/lib
-llapack
和 -lblas
:链接 LAPACK 和 BLAS 库。-L/path/to/libs
:指定库文件所在目录。my_c_func.c
#include <stdio.h>
void say_hello() {
printf("Hello from C!\n");
}
main.f90
program main
implicit none
interface
subroutine say_hello() bind(C, name="say_hello")
end subroutine
end interface
call say_hello()
end program main
gcc -c my_c_func.c -o my_c_func.o # 编译 C 文件
gfortran main.f90 my_c_func.o -o mixed # 编译 Fortran 并链接 C 对象文件
./mixed # 运行
输出:
Hello from C!
使用 gdb
调试:
gfortran -g hello.f90 -o hello_debug # 编译时加入调试信息
gdb ./hello_debug # 启动 gdb
在 gdb
中常用命令:
run
:运行程序break main
:在 main
函数设置断点next
:单步执行print variable
:打印变量值如果需要同时使用多个版本的 gfortran
(如 9 和 10):
# Ubuntu/Debian
sudo apt install gfortran-9 gfortran-10
# 切换版本(临时)
sudo update-alternatives --config gfortran
按提示选择版本编号。
gfortran: command not found
PATH
。-Wall
检查)。-fcheck=all
检测)。# 查找库位置
find /usr -name "liblapack*"
# 显式指定路径
gfortran program.f90 -o program -L/usr/local/lib -llapack -lblas
没有搜到相关的文章
领取专属 10元无门槛券
手把手带您无忧上云