Fortran/Hello world

出典: フリー教科書『ウィキブックス(Wikibooks)』

簡単なFortranプログラム[編集]

以下は簡単なFortranのプログラムです。

コンパイル・実行例
program hello
    print *, "Hello World!"
end program
実行結果
 Hello World!

Fortranは大文字と小文字を区別しないので、最初のプログラムは次のようにこともできます。

Program Hello
    Print *, "Hello World!"
End Program

このプログラムでは、大文字小文字を区別されるのは、print文の引用符で囲まれた部分("Hello World!")だけです。

オンラインのコンパイル・実行環境

OnlineGDB の様な、オンラインのコンパイル・実行環境であればウェブブラウザーだけで、Fortranのプログラムをコンパイル・実行できます。

上の例の、コンパイル・実行例 のようなリンク先を開くと、ウェブブラウザー上でコンパイル・実行することが出来ます。


コンパイル・実行環境[編集]

上のコラムで紹介した「オンラインのコンパイル・実行環境」には、次のような特性があります。

長所
ネットワーク環境とウェブブラウザーさえあればコンパイル・実行できる。
コードの共有を URL を介してできる。
短所
エディターなどの、使い慣れた開発ツールが使えない。
標準入力を使うプログラムの実行に向かない。
言語処理系の選択の幅が少ない(ない)

短所か問題になる場合は、自らコンパイル実行環境を構築することで解決する必要があります。

環境構築[編集]

gfortran[編集]

g95, flang などいくつかのオープン・ソース・ソフトウェアの Fortran 言語処理系がありますが、ここでは GNUプロジェクトのGCC(GNU Compiler Collection)のFortranフロントエンド gfortran を紹介します。

OnlineGDB でも、gfortran-11.3.0 が使われています。

gfortran -v
Program Hello
    call system("gfortran -v")
End Program
実行結果
Using built-in specs.
COLLECT_GCC=gfortran
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.3.0-1ubuntu1~22.04' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-xKiWfi/gcc-11-11.3.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-xKiWfi/gcc-11-11.3.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 11.3.0 (Ubuntu 11.3.0-1ubuntu1~22.04)

GNU/Linux[編集]

ディストリビューションにより、パッケージマネージャとパッケージ体系に違いがありますが、

Debian[編集]
root@penguin:~# uname -a
Linux penguin 6.1.60-08594-g03a802b9a072 #1 SMP PREEMPT_DYNAMIC Fri Jan 12 18:20:08 PST 2024 x86_64 GNU/Linux
root@penguin:~# apt-get install gfortran-14
Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following additional packages will be installed:
  gfortran-14-x86-64-linux-gnu libgfortran-14-dev libgfortran5
Suggested packages:
  gfortran-14-multilib gfortran-14-doc libcoarrays-dev
The following NEW packages will be installed:
  gfortran-14 gfortran-14-x86-64-linux-gnu libgfortran-14-dev libgfortran5
0 upgraded, 4 newly installed, 0 to remove and 0 not upgraded.
Need to get 93.1 MB of archives.
After this operation, 366 MB of additional disk space will be used.
Do you want to continue? [Y/n] 
Get:1 https://deb.debian.org/debian trixie/main amd64 libgfortran5 amd64 14-20240201-3 [836 kB]
Get:2 https://deb.debian.org/debian trixie/main amd64 libgfortran-14-dev amd64 14-20240201-3 [880 kB]
Get:3 https://deb.debian.org/debian trixie/main amd64 gfortran-14-x86-64-linux-gnu amd64 14-20240201-3 [91.3 MB]
Get:4 https://deb.debian.org/debian trixie/main amd64 gfortran-14 amd64 14-20240201-3 [2,688 B]                                                                                                
Fetched 93.1 MB in 15s (6,007 kB/s)                                                                                                                                                            
Selecting previously unselected package libgfortran5:amd64.
(Reading database ... 78087 files and directories currently installed.)
Preparing to unpack .../libgfortran5_14-20240201-3_amd64.deb ...
Unpacking libgfortran5:amd64 (14-20240201-3) ...
Selecting previously unselected package libgfortran-14-dev:amd64.
Preparing to unpack .../libgfortran-14-dev_14-20240201-3_amd64.deb ...
Unpacking libgfortran-14-dev:amd64 (14-20240201-3) ...
Selecting previously unselected package gfortran-14-x86-64-linux-gnu.
Preparing to unpack .../gfortran-14-x86-64-linux-gnu_14-20240201-3_amd64.deb ...
Unpacking gfortran-14-x86-64-linux-gnu (14-20240201-3) ...
Selecting previously unselected package gfortran-14.
Preparing to unpack .../gfortran-14_14-20240201-3_amd64.deb ...
Unpacking gfortran-14 (14-20240201-3) ...
Setting up libgfortran5:amd64 (14-20240201-3) ...
Setting up libgfortran-14-dev:amd64 (14-20240201-3) ...
Setting up gfortran-14-x86-64-linux-gnu (14-20240201-3) ...
Setting up gfortran-14 (14-20240201-3) ...
Processing triggers for libc-bin (2.37-15~deb13u1) ...
root@penguin:~# gfortran-14 -v
Using built-in specs.
COLLECT_GCC=gfortran-14
COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-linux-gnu/14/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Debian 14-20240201-3' --with-bugurl=file:///usr/share/doc/gcc-14/README.Bugs --enable-languages=c,ada,c++,go,d,fortran,objc,obj-c++,m2,rust --prefix=/usr --with-gcc-major-version-only --program-suffix=-14 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/libexec --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-libstdcxx-backtrace --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --enable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/reproducible-path/gcc-14-14-20240201/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/reproducible-path/gcc-14-14-20240201/debian/tmp-gcn/usr --enable-offload-defaulted --without-cuda-driver --enable-checking=yes,extra,rtl --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 14.0.1 20240131 (experimental) [master r14-8680-g2f14c0dbb78] (Debian 14-20240201-3)
Fedora Linux[編集]
$ sudo dnf install gfortran

Windows[編集]

いく通りかの方法がありますが、MSYS2環境にMinGW64の一部として、gfortran をインストールする方法を紹介します。

MSYS2/MinGW64のパッケージマネージャは、Arch Linux 由来の pacman(1) です。

MINGW64
user@host MINGW64 ~
$ pacman -Syuu
 mingw32 is up to date
 mingw64 is up to date
 ucrt64 is up to date
 clang64 is up to date
 msys is up to date
user@host MINGW64 ~
$ pacman -S base-devel mingw-w64-x86_64-toolchain
  1. プロンプトに MINGW64 があることを確認してください
  2. まず、パッケージシステムを最新にします(いくつか質問があるかもしれません)。
  3. base-devel と mingw-w64-x86_64-toolchain をインストールします。
    base-devel
    基本的な開発用ユーティリティを集めたメタパッケージ
    asciidoc autoconf autoconf2.13 autogen automake-wrapper automake1.10 automake1.11 automake1.12 automake1.13 automake1.14 automake1.15 automake1.16 automake1.6 automake1.7 automake1.8 automake1.9 bison btyacc diffstat diffutils dos2unix file flex gawk gdb gettext gettext-devel gperf grep groff help2man texinfo texinfo-tex intltool libtool libunrar libunrar-devel unrar m4 make man-db pacman patch patchutils perl pkgconf pkgfile quilt reflex scons sed swig ttyrec wget xmlto
    mingw-w64-x86_64-toolchain
    MSYS2/MinGW64用のセルフ開発用ユーティリティを集めたメタパッケージ
    mingw-w64-x86_64-binutils mingw-w64-x86_64-crt-git mingw-w64-x86_64-gcc mingw-w64-x86_64-gcc-ada mingw-w64-x86_64-gcc-fortran mingw-w64-x86_64-gcc-libgfortran mingw-w64-x86_64-gcc-libs mingw-w64-x86_64-gcc-objc mingw-w64-x86_64-libgccjit mingw-w64-x86_64-gdb mingw-w64-x86_64-gdb-multiarch mingw-w64-x86_64-headers-git mingw-w64-x86_64-libmangle-git mingw-w64-x86_64-libwinpthread-git mingw-w64-x86_64-winpthreads-git mingw-w64-x86_64-make mingw-w64-x86_64-pkgconf mingw-w64-x86_64-tools-git mingw-w64-x86_64-winstorecompat-git
MinGW・MSYSの関係
MinGW
GNUツールチェーンのWindows向け移植版
公式サイトのドメインが失効
MinGW-w64
MinGW のフォーク。
64bit/32bit両対応。
ucrtにも対応強化中。
clang64にも対応強化中。
MSYS
MinGW 上のPOSIX環境。
POSIX環境は、Cygwin のフォーク。
MSYS2
MinGW-w64 上のPOSIX環境。
POSIX環境は、Cygwin のフォーク。

今回はMSYS2をインストールして、 pacman を使ってツールチェーンを用意しました。

それぞれのソフトウェア群の開発用状況は日々変わりますので、現在(2021年8月)の状況と最新の状況は異なるかもしれません。


使い方・注意点[編集]

コンパイラーのバージョンの確認[編集]

環境が構築できたら、コンパイラーのバージョンを確認します。

コンパイラーのバージョンの確認
$ gfortran -v
実行結果
user@hostname MINGW64 ~
Using built-in specs.
COLLECT_GCC=C:\msys64\mingw64\bin\gfortran.exe
COLLECT_LTO_WRAPPER=C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/10.3.0/lto-wrapper.exe
Target: x86_64-w64-mingw32
Configured with: ../gcc-10.3.0/configure --prefix=/mingw64 --with-local-prefix=/mingw64/local --build=x86_64-w64-mingw32 --host=x86_64-w64-mingw32 --target=x86_64-w64-mingw32 --with-native-system-header-dir=/mingw64/x86_64-w64-mingw32/include --libexecdir=/mingw64/lib --enable-bootstrap --enable-checking=release --with-arch=x86-64 --with-tune=generic --enable-languages=c,lto,c++,fortran,ada,objc,obj-c++,jit --enable-shared --enable-static --enable-libatomic --enable-threads=posix --enable-graphite --enable-fully-dynamic-string --enable-libstdcxx-filesystem-ts=yes --enable-libstdcxx-time=yes --disable-libstdcxx-pch --disable-libstdcxx-debug --enable-lto --enable-libgomp --disable-multilib --disable-rpath --disable-win32-registry --disable-nls --disable-werror --disable-symvers --with-libiconv --with-system-zlib --with-gmp=/mingw64 --with-mpfr=/mingw64 --with-mpc=/mingw64 --with-isl=/mingw64 --with-pkgversion='Rev5, Built by MSYS2 project' --with-bugurl=https://github.com/msys2/MINGW-packages/issues --with-gnu-as --with-gnu-ld --with-boot-ldflags='-pipe -Wl,--dynamicbase,--high-entropy-va,--nxcompat,--default-image-base-high -Wl,--disable-dynamicbase -static-libstdc++ -static-libgcc' 'LDFLAGS_FOR_TARGET=-pipe -Wl,--dynamicbase,--high-entropy-va,--nxcompat,--default-image-base-high' --enable-linker-plugin-flags='LDFLAGS=-static-libstdc++\ -static-libgcc\ -pipe\ -Wl,--dynamicbase,--high-entropy-va,--nxcompat,--default-image-base-high\ -Wl,--stack,12582912'
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 10.3.0 (Rev5, Built by MSYS2 project)
user@hostname MINGW64 ~
$

上の例は、Windows 11 上の MSYS2 / MinGW64 上の、gfortran-10.3.0です。環境によって gfortran のコマンド名に prefix や suffix か付く場合があります。

例えば、FreeBSDでは複数のバージョンのGCCパッケージが共存できるようバージョンごとにsuffixが付き gfortran12 の様なコマンド名になります。

コンパイルテスト[編集]

テキストエディタなどで hello.f90 を用意し、

hello.f90
Program Hello
    Print *, "Hello World!"
End Program

コマンドラインから、

gfortran hello.f90 -o hello

とすると、ソースコード hello.f90 から 実行形式 hello をコンパイルします(WinowsやOpenVMSでは、 .EXE の様な拡張子が暗黙に追加されるかもしれません)

gfortran ではデフォルトでFORTRAN 77規格を使用します(FORTRAN 77標準で使用されている固定形式のフォーマットが要求される)。 このため、自由形式のフォーマットを有効にするには、ソースファイルの拡張子を .f90(またはそれ以降の規格)のにして、コンパイラが希望する規格を自動的に推測できるようにしなければなりません。ほかにも、コマンドラインから -ffree-form オプションをコンパイラに渡すことでソースファイルの拡張子が .f でも自由形式のフォーマットを有効にすることができます。

インデント

(フリーフォーム記法の)Fortranの文法上はインデント(字下げ)は不要です。つまり

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

のように記述しても実行可能です。しかし、インデントをしない書き方は、可読性が下がるので、あまり推奨できません。


脚註[編集]