在 Ubuntu 上测试(编写、编译、运行)Fortran 程序,一般按下面步骤来:
Ubuntu 默认通常没有 Fortran 编译器,需要先安装 gfortran:
sudo apt update
sudo apt install gfortran
安装完成后检查版本:
gfortran --version
新建文件,例如 hello.f90:
program hello
print *, "Hello, Fortran!"
end program hello
gfortran hello.f90 -o hello
hello.f90:源文件-o hello:生成可执行文件 hello./hello
输出应为:
Hello, Fortran!
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
-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
.f90:现代 Fortran(推荐).f:老式 Fortran 77gfortran main.f90 sub.f90 -o program
gfortran -Wall -Wextra hello.f90 -o hello
如果你是想测试 Fortran 是否可用、做科学计算、运行老代码或用 Makefile / CMake,可以告诉我具体需求,我可以给你更针对性的示例。