Cannot open include file: 'gmp.h': No such file or directory (Python/Cython)

2.2k views Asked by At

I was learning how to integrate gmpy2 with Cython. From the docs, I was provided with an example code. Since I am not really sure about what was going on, I felt that I can learn how to use gmpy in Cython by playing with the example code provided.

The example code:
setup.py

   "A minimal setup.py for compiling test_gmpy2.pyx"
    
    from distutils.core import setup
    from distutils.extension import Extension
    from Cython.Build import cythonize
    import sys
    
    ext = Extension("test_gmpy2", ["test_gmpy2.pyx"], include_dirs=sys.path, libraries=['gmp', 'mpfr', 'mpc'])
    
    setup(
        name="cython_gmpy_test",
        ext_modules=cythonize([ext], include_path=sys.path)
    )

test_gmpy2.pyx

    "A minimal cython file test_gmpy2.pyx"

    from gmpy2 cimport *
    
    cdef extern from "gmp.h":
        void mpz_set_si(mpz_t, long)
    
    import_gmpy2()   # needed to initialize the C-API
    
    cdef mpz z = GMPy_MPZ_New(NULL)
    mpz_set_si(MPZ(z), -7)
    
    print(z + 3)

Running setup.py gives me this error:

fatal error C1083: Cannot open include file: 'gmp.h': No such file or directory

What is wrong? How do I fix it? I checked my install for gmpy. I believe there isn't anything wrong with it.

1

There are 1 answers

0
GBy On

I can provide a working example. The package fractalshades includes a Cython extension which imports (cimport) gmpy2 and is compiled both under Linux and Windows.

The code for the Cython extension is hosted here https://github.com/GBillotey/Fractalshades/blob/master/src/fractalshades/mpmath_utils/FP_loop.pyx

The key parts to compile for windows (with MS Visual Studio) have been :

  • includes the headers in gmpy2 installation directory
  • An import library (.lib file) is necessary when calling functions in a dll - it provides the stubs that hook up to the DLL at runtime. To generate these .lib one can use dumpbin & lib executables provided by visual studio.

For implementation details, the Windows build is run on a github runner with the full script available as a Github workflow.