LoginSignup
2
1

More than 3 years have passed since last update.

C++からFortranでHello Worldする

Posted at

はじめに

普段はC++でコードを書いていますが、Fortranの遺産も使いたくなったので入門してみました。

環境

  • OS: Mac OS X Mojave 10.14.6
  • gfortran: Homebrew GCC 9.3.0_1
  • g++(g++-9): Homebrew GCC 9.3.0_1

コンパイラのインストール

MacでHomebrewを使用する場合、下記コマンドで一発です。

$ brew install gcc

Windowsの場合、MinGWなどを使用すると良いでしょう。

サンプルコード

main.cpp
#include <iostream>

extern "C" {
    void hello();
}

int main(int argc, char *argv[]) {
    hello();
    return 0;
}
hello.f90
subroutine hello() bind(c)
  implicit none
  print *, 'Hello World!'
end subroutine

ポイント

  • hello関数をFortranのサブルーチンとして作成します。
  • extern "C"することで、C言語とFortranの連携を使います。

コンパイル

$ gfortran -c hello.f90
$ g++ -lgfortran main.cpp hello.o
$ ./a.out
 Hello World!

Macの場合、付属のclangではなくgccを使います。
g++をg++-9などで置き換えることで使用できるはずです。
数字はバージョンに応じて変えてください。
-lgfortranをつけることを忘れずに。
なお、WindowsでMinGWを使用した場合、この方法だとうまくいきませんでした。
一度dllを経由するのが良いようです。

Windows用
$ gfortran --shared -o hello.dll hello.f90
$ g++ -L ./ main.cpp -lhello
$ a.exe
 Hello World!

CMakeを使用してのコンパイル

環境に応じて書き換えるのも面倒なので、CMakeに任せてみました。こちらもMacの場合インストールにHomebrewが使用できます。

CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
enable_language(Fortran)
project(hello_world CXX Fortran)

add_executable(
    a.out
    hello.f90 
    main.cpp
)

ポイント

  • enable_languageでFortranを有効にします。
  • 使用言語にCXXとFortranを指定します。

ビルド

$ mkdir build
$ cd build
$ cmake ..
$ make
$ ./a.out
 Hello World!

ビルド用のディレクトリを作ってCMakeにMakefileを作ってもらい、makeします。
Windowsの場合は、cmakeの際に -G "Unix Makefiles" などのオプションを付けてください。
付けないとVisual Studio用のファイルを作ろうとして詰まります。

終わりに

FortranのサブルーチンをC++から呼び出すことができました。
C言語とFortranの連携をC++から使用しているだけなので、C言語との連携について調べることでより高度な連携も可能なはずです。

参考文献

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1