f2py is not able to link with NetCDF library -

259 views Asked by At

I am trying install some Python modules in my system using f2py, which are related to an ocean model (in Fortran 90). I am facing some problems with f2py. To be specific, the f2py is unable to link with the NetCDF library even though I have the required library and include files installed. I am using Python 2.7 with Anaconda 2 on Ubuntu16.04 on a 64-bit machine. I'm using gfortran.

To test it's working, I wrote a small code - an f90 module that contains a small subroutine. The subroutine performs a basic math task, and calls a NetCDF routine that prints the NetCDF version installed. The module (testsub.f90) is as follows:

module testsub
implicit none

contains

subroutine f_sum(a, b, s)
!#include 'netcdf.inc' 
  use netcdf
  real(8) :: a, b, s
  s = a+b;

  !Calls a function that prints the netcdf version
  write(*,*) trim(nf90_inq_libvers())
end subroutine f_sum

end module

The makefile for testsub is:

#Fortran compiler
FC=gfortran

NCLIB = -L/home/sonaljit/anaconda2/lib -lnetcdf -lnetcdff -L/usr/lib/python2.7/config-x86_64-linux-gnu -lpython2.7
NCINC = -I/home/sonaljit/anaconda2/include

#f2py and flags
F2PY = /home/sonaljit/anaconda2/bin/f2py
PYFLAGS = "-fPIC -g -O2 -fdefault-real-8"

pytest : testsub.f90
        $(F2PY) --fcompiler=$(FC) --f90flags=$(PYFLAGS) -c $(NCINC) -m testpymod testsub.f90 $(NCLIB)

clean :
        rm testpymod.so

I have the NetCDF library and include files installed in the given paths. When I run the makefile using make pytest, I get the following error:

/usr/bin/ld: /home/sonaljit/anaconda2/lib/libnetcdf.a(netcdf.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
/home/sonaljit/anaconda2/lib/libnetcdf.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status

However, I am not seeing this error when I am commenting out the NetCDF lines in the module. It seems f2py is not able to link to NetCDF routines. What can be the error here? Is it due to the structure of the code? Or, do I need to include some other library?

1

There are 1 answers

2
Vladimir F Героям слава On

You are compiling a shared (dynamic) library and you should use a shared library version of NetCDF.

If you installed NetCDF yourself (as suggested by the path in your /home/sonaljit), you should install the .so version and link with this version.