温馨提示×

ubuntu怎么测试fortran

小樊
35
2026-10-15 22:39:19
栏目: 智能运维

在 Ubuntu 上测试(编写、编译、运行)Fortran 程序,一般按下面步骤来:


一、安装 Fortran 编译器

Ubuntu 默认通常没有 Fortran 编译器,需要先安装 gfortran:

sudo apt update
sudo apt install gfortran

安装完成后检查版本:

gfortran --version

二、写一个最简单的 Fortran 程序

新建文件,例如 hello.f90:

program hello
    print *, "Hello, Fortran!"
end program hello

三、编译 Fortran 程序

gfortran hello.f90 -o hello
  • hello.f90:源文件
  • -o hello:生成可执行文件 hello

四、运行程序

./hello

输出应为:

 Hello, Fortran!

五、测试更复杂的例子(可选)

1. 数值计算示例

program sum_test
    implicit none
    integer :: i, s
    s = 0
    do i = 1, 100
        s = s + i
    end do
    print *, "Sum 1 to 100 =", s
end program sum_test

编译运行:

gfortran sum_test.f90 -o sum_test
./sum_test

2. 使用数学库(如 -lm)

program math_test
    implicit none
    real :: x
    x = sqrt(2.0)
    print *, "sqrt(2) =", x
end program math_test

编译:

gfortran math_test.f90 -o math_test -lm

六、常见问题

1. 文件后缀

  • .f90:现代 Fortran(推荐)
  • .f:老式 Fortran 77

2. 编译多个文件

gfortran main.f90 sub.f90 -o program

3. 查看编译警告

gfortran -Wall -Wextra hello.f90 -o hello

如果你是想测试 Fortran 是否可用、做科学计算、运行老代码或用 Makefile / CMake,可以告诉我具体需求,我可以给你更针对性的示例。

0 踩