使用 NetCDF 的 R CMD SHLIB Fortran 90 文件

R CMD SHLIB Fortran 90 file which use NetCDF

我想编译一个使用NetCDF 的fortran 90 文件。我已经安装 NetCDF-Fortran and as shown here,编译文件 test_nc.f90:

program test_nc
    use netcdf
    implicit none
    integer :: ncid, nc_err

    nc_err = nf90_open('test.nc', nf90_nowrite, ncid)
    nc_err = nf90_close(ncid)
end program test_nc

用gfortran编译是

gfortran test_nc.f90 -o test_nc `nf-config --fflags --flibs`

其中 nf-config --fflags --flibs 是:

-I/usr/include
-L/usr/lib -lnetcdff -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -lnetcdf -lnetcdf -ldl -lz -lcurl -lm

用子程序代替程序是

subroutine test_nc
    use netcdf
    implicit none
    integer :: ncid, nc_err

    nc_err = nf90_open('test.nc', nf90_nowrite, ncid)
    nc_err = nf90_close(ncid)
end subroutine test_nc

然而,当我运行

R CMD SHLIB test_nc.f90  `nf-config --fflags --flibs`

结果:

gfortran -fno-optimize-sibling-calls  -fpic  -g -O2 -fdebug-prefix-map=/build/r-base-k1TtL4/r-base-3.6.1=. -fstack-protector-strong  -c  test_nc.f90 -o test_nc.o
test_nc.f90:2:8:

    2 |     use netcdf
      |        1
Fatal Error: Cannot open module file ‘netcdf.mod’ for reading at (1): No such file or directory
compilation terminated.

此外,当我尝试时:

R CMD SHLIB test_nc.f90 -I/usr/include -L/usr/lib -lnetcdff -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-z,now -lnetcdf -lnetcdf -ldl -lz -lcurl -lm
gfortran -fno-optimize-sibling-calls  -fpic  -g -O2 -fdebug-prefix-map=/build/r-base-k1TtL4/r-base-3.6.1=. -fstack-protector-strong  -c  test_nc.f90 -o test_nc.o

结果:

test_nc.f90:2:8:

    2 |     use netcdf
      |        1
Fatal Error: Cannot open module file ‘netcdf.mod’ for reading at (1): No such file or directory
compilation terminated.
make: *** [/usr/lib/R/etc/Makeconf:195: test_nc.o] Error 1

如何告诉 R CMD SHLIB 使用 Netcdf-fortran 库?

?SHLIB 显示

R CMD SHLIB -o mylib.so a.f b.f -L/opt/acml3.5.0/gnu64/lib -lacml

所以我想这样做是可能的

在对 R CMD SHLIB 的调用中,您从 nf-config 提供的选项仅作为 linker 选项。编译步骤失败,因为在 link 进程之前需要设置 NetCDF Fortran 模块的搜索路径。

要从 nf-config 添加 -I... 选项,您可以使用环境变量 PKG_FCFLAGS:

env PKG_FCFLAGS="`nf-config --fflags`" R CMD SHLIB test_nc.f90 `nf-config --flibs`

或者,您可以将 PKG_FCFLAGS 放入您的 Makevars 文件中。

(请注意,与 C 和 C++ 不同,模块文件的包含路径选项不适用于预处理阶段。)