Search code examples
python-3.xmakefilecpythonf2py

Makefile for f2py in python3


In order to build extension modules using f2py in python2, I have been using a Makefile similar to:

default: fortran_lib.so

%.so::  %.f90
    f2py -c -m $* $<

For completeness, here is also a dummy fortran_lib.f90 file

subroutine square(d)
implicit none
!f2py intent(inout) d
integer, intent(inout)  ::  d

d = d*d
end subroutine square

This used to work fine, make would simply produce fortran_lib.so.

Now I would like to support python3 as well, but when using f2py3, make produces the versioned fortran_lib.cpython-35m-x86_64-linux-gnu.so instead (on my particular setup).

Since this differs from the specified target name, make has no way of recognising that the target has already been made. Accordingly, it remakes the target every time you run make.

How do I get around this problem (without having to hardcode the version)?

  • Can I tell f2py3 to turn off versioning?
  • Can I somehow work around the versioning in the Makefile?
  • Or am I forced to switch to other tools for building the extension modules (distutils,...)?

Solution

  • My recommendation is to leave the versioning on (it was invented for a reason...) and instead work out what the suffix it uses is. The command python3-config --extension-suffix gets that.

    Therefore the makefile looks like

    EXT_SUFFIX := $(shell python3-config --extension-suffix)
    
    default: fortran_lib$(EXT_SUFFIX)
    
    %$(EXT_SUFFIX): %.f90
        f2py3 -c -m $* $<
    

    (I'm not sure whether shell is a GNU extension and if so, whether it will reduce portability. That may be something to consider.)


    If you're really keen on losing the suffix then you should probably just add a second step to the rule, something like:

    %.so::  %.f90
        f2py3 -c -m $* $<
        mv $*$(EXT_SUFFIX) $@
    

    If you don't want to use shell to get EXT_SUFFIX then you could probably come up with a wildcard that works.

    I think this second option is worse that the first...