2012-04-11 39 views
5

我想了解如何在Linux下动态创建并链接Fortran中的共享库。Fortran中的共享库,最小示例不起作用

我有两个文件:第一个,liblol.f90,看起来是这样的:

subroutine func() 
    print*, 'lol!' 
end subroutine func 

gfortran -shared -fPIC -o liblol.so liblol.f90

第二个文件,main.f90编译它,看起来是这样的:

program main 
    call func() 
end program main 

当我现在尝试使用命令gfortran -L. -llol main.f90 -o main进行编译时,出现以下错误:

/tmp/ccIUIhcE.o: In function `MAIN__': 
main.f90:(.text+0xa): undefined reference to `func_' 
collect2: ld returned 1 exit status 

我不明白为什么它说:“未定义的引用”,因为nm -D liblol.so输出给了我这样的:

    w _Jv_RegisterClasses 
0000000000201028 A __bss_start 
       w __cxa_finalize 
       w __gmon_start__ 
0000000000201028 A _edata 
0000000000201038 A _end 
0000000000000778 T _fini 
       U _gfortran_st_write 
       U _gfortran_st_write_done 
       U _gfortran_transfer_character_write 
0000000000000598 T _init 
00000000000006cc T func_ 

是否有其他任何需要的参数?

回答

8

必须被唯一改变的是参数的顺序,如

gfortran -L. main.f90 -llol -o main 

是的,只有main.f90时和-llol是相反的。我希望这能拯救一个人,让他在这一年中失去一生。在相关说明中,如果您试图编译使用LAPACK或BLAS的程序(这对我不起作用,并且为什么我首先尝试自己创建共享库),这同样适用。 编写源文件的第一名称:

gfortran mylapack.f90 -llapack -lblas -o mylapack 

这样做的原因可以在手册页中找到,看到的http://gcc.gnu.org/onlinedocs/gcc/Link-Options.html顶部的选项-l:

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in `z', those functions may not be loaded.