2.3. GNU Fortran Compiler
2.3.1. 安装 Fortran Compiler 复制链接链接已复制到粘贴板!
在 Red Hat Developer Toolset 中,GNU Fortran 编译器由 devtoolset-11-gcc-gfortran 软件包提供,并自动安装 devtoolset-11-toolchain,如 第 1.5 节 “安装 Red Hat Developer Toolset” 所述。
2.3.2. 使用 Fortran Compiler 复制链接链接已复制到粘贴板!
要在命令行上编译 Fortran 程序,请运行 gfortran 编译器,如下所示:
scl enable devtoolset-11 'gfortran -o output_file source_file...'
$ scl enable devtoolset-11 'gfortran -o output_file source_file...'
这会在当前工作目录中创建一个名为 output_file 的二进制文件。如果省略了 -o 选项,则编译器默认创建名为 a.out 的文件。
当您处理由多个源文件组成的项目时,首先编译每个源文件的对象文件,然后将这些目标文件链接在一起。这样,当您更改单个源文件时,您只能编译此文件,而无需编译整个项目。在命令行中编译目标文件:
scl enable devtoolset-11 'gfortran -o object_file -c source_file'
$ scl enable devtoolset-11 'gfortran -o object_file -c source_file'
这会创建一个名为 object_file 的对象文件。如果省略了 the -o 选项,编译器会创建一个名为 的文件,其源文件带有 .o 文件扩展名。将目标文件链接在一起并创建二进制文件:
scl enable devtoolset-11 'gfortran -o output_file object_file...'
$ scl enable devtoolset-11 'gfortran -o output_file object_file...'
请注意,您可以使用 scl 工具执行任何命令,从而导致它使用等效的 Red Hat Developer Toolset 二进制文件来运行它。这可让您默认使用 Red Hat Developer Toolset gfortran 运行 shell 会话:
scl enable devtoolset-11 'bash'
$ scl enable devtoolset-11 'bash'
验证您在任何时候正在使用的 gfortran 版本:
which gfortran
$ which gfortran
Red Hat Developer Toolset 的 gfortran 可执行路径以 /opt 开头。另外,您可以使用以下命令确认版本号与 Red Hat Developer Toolset gfortran 的版本号匹配:
gfortran -v
$ gfortran -v
例 2.5. 在命令行中编译 Fortran 程序
考虑名为 hello.f 的源文件,其内容如下:
program hello print *, "Hello, World!" end program hello
program hello
print *, "Hello, World!"
end program hello
使用 Red Hat Developer Toolset 中的 gfortran 编译器在命令行中编译此源代码:
scl enable devtoolset-11 'gfortran -o hello hello.f'
$ scl enable devtoolset-11 'gfortran -o hello hello.f'
这会在当前工作目录中创建一个名为 hello 的新二进制文件。
2.3.3. 运行 Fortran 程序 复制链接链接已复制到粘贴板!
当 gfortran 编译程序时,它会创建一个可执行的二进制文件。要在命令行中运行程序,请切换到具有可执行文件的目录,并运行以下命令:
./file_name
$ ./file_name
例 2.6. 在命令行中运行 Fortran 程序
假设您已成功编译了 hello 二进制文件,如 例 2.5 “在命令行中编译 Fortran 程序” 所示,您可以运行它:
./hello
$ ./hello
Hello, World!