LoginSignup
1
3

More than 5 years have passed since last update.

Fortranでの静的ライブラリのリンクとmodule

Posted at

"fortranの静的ライブラリと問題点"
https://qiita.com/blu_epos_t59/items/1a88230698f5de9cb615
という記事に、Fortranの静的ライブラリを作る記事があるが、

ただし、調べてみたところどうやら読まれるのは宣言部、つまりcontains以下のみであり、subroutineしかまとめることができないらしい。定数はおろか構造体やクラスもまとめることができない。

及び、

なので、moduleのソースをどこかにまとめて置いておいてmakefileでその都度一緒にコンパイルするほうがいいと思う。

とあった。これではmoduleを使った場合に非常に面倒なので、2019年現在どうなっているか調べてみた。

バージョン

gcc version 7.2.0 (Homebrew GCC 7.2.0_1)

コード

記事にあるものと同じ、単純なモジュールを考える。

mylib.f90
module mylib
   implicit none
   integer :: mynum = 100
   type myclass
      integer :: id
   end type myclass
contains 
   subroutine myroutine()
      write(6,*) "hello world!"
   end subroutine myroutine
end module mylib

また、Makefileを

all:mylib.f90
    gfortran -c mylib.f90 -o mylib.o
    ar cr libmylib.a mylib.o

とした。

これをtestディレクトリに置く。そして、

test.f90
program main
    use mylib
    implicit none
    type(myclass)::a
    write(*,*) mynum
    a%id = 4
    write(*,*) a%id

    call myroutine()
end

をその上のディレクトリに置いてみよう。つまり、

test        test.f90

で、testの中身は

Makefile    mylib.f90

という状況とする。

make

testディレクトリ内で

make

をすると、

ls
Makefile    libmylib.a  mylib.f90   mylib.mod   mylib.o

となる。次に、その上のtest.f90のあるディレクトリに行って、

gfortran test.f90 -L./test/  -lmylib

としてみたが、

test.f90:2:8:

     use mylib
        1
Fatal Error: Can't open module file 'mylib.mod' for reading at (1): No such file or directory
compilation terminated.

というエラーが出た。つまり、moduleを探すことができていない。
そこで、
https://software.intel.com/en-us/forums/intel-fortran-compiler-for-linux-and-mac-os-x/topic/510065
を参考にして、

gfortran test.f90 -L./test/ -I./test -lmylib

とすると、ちゃんとコンパイルできて、出力は

./a.out 
         100
           4
 hello world!

となった。

まとめ

今回使ったgfortranのバージョンでは、記事の問題を再現できなかった。一方、modがないと言われる件に関しては、Iオプションをつけることで解決することができた。

1
3
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
1
3