OCTOPUSで、FortranとC/C++のソースコードが混在したプログラムをビルドする方法を解説します。言語によってランタイム・標準ライブラリが異なるため、複数の言語が混在するプログラムをリンクするためには、正しい標準ライブラリを指定する必要があります。
なお、コンパイラは、BaseCPUモジュールに含まれるIntel oneAPI DPC++/C++ Compiler (icx/icpx) および Intel Fortran Compiler (ifx) を用います。
FortranのメインプログラムからCの関数を呼び出す場合
以下のようにmain.f90でメインプログラムが、hello.cで関数helloが定義されているとします。
1 2 3 4 5 6 7 8 |
program main implicit none interface subroutine hello() bind(c) end subroutine end interface call hello end program |
1 2 3 4 5 6 |
#include <stdio.h> void hello() { printf("hello, world\n"); } |
各言語のコンパイラでソースコードをコンパイルした後、Fortranコンパイラでオブジェクトをリンクして実行可能ファイルを生成します。
ifx -c main.f90 # Fortranのソースコードをコンパイル
icx -c hello.c # Cのソースコードをコンパイル
ifx -o hello main.o hello.o # オブジェクトをリンク
Cコンパイラでオブジェクトをリンクする事もできます。その場合は、-fortlibオプションでFortranの標準ライブラリをリンクしてください。
icx -o hello -fortlib main.o hello.o # オブジェクトをリンク
FortranのメインプログラムからC++の関数を呼び出す場合
以下のようにmain.f90でメインプログラムが、hello.cppで関数helloが定義されているとします。
1 2 3 4 5 6 7 8 |
program main implicit none interface subroutine hello() bind(c) end subroutine end interface call hello end program |
1 2 3 4 5 6 |
#include <iostream> extern "C" void hello() { std::cout << "hello, world" << std::endl; } |
各言語のコンパイラでソースコードをコンパイルした後、Fortranコンパイラでオブジェクトをリンクして実行可能ファイルを生成します。その際に、-cxxlibオプションでC++の標準ライブラリをリンクしてください。
ifx -c main.f90 # Fortranのソースコードをコンパイル
icpx -c hello.cpp # C++のソースコードをコンパイル
ifx -o hello -cxxlib main.o hello.o # オブジェクトをリンク
C++コンパイラでオブジェクトをリンクする事もできます。その場合は、-fortlibオプションでFortranの標準ライブラリをリンクしてください。
icpx -o hello -fortlib main.o hello.o # オブジェクトをリンク
Cのメイン関数からFortranのサブルーチンを呼び出す場合
以下のようにmain.cでメイン関数が、hello.f90でサブルーチンhelloが定義されているとします。
1 2 3 4 5 6 7 8 |
extern void hello_(); int main() { hello_(); return 0; } |
1 2 3 4 5 |
subroutine hello implicit none print *,'hello, world' end subroutine hello |
各言語のコンパイラでソースコードをコンパイルした後、Cコンパイラでオブジェクトをリンクして実行可能ファイルを生成します。その際に、-fortlibオプションでFortranの標準ライブラリをリンクしてください。
ifx -c main.f90 # Fortranのソースコードをコンパイル
icpx -c hello.c # Cのソースコードをコンパイル
icx -o main -fortlib main.o hello.o # オブジェクトをリンク
Fortranコンパイラでオブジェクトをリンクする事もできます。その場合は、-nofor-mainオプションでメインプログラムがFortranでないことを指示してください。
ifx -o main -nofor-main main.o hello.o # オブジェクトをリンク