Skip to content Skip to sidebar Skip to footer

Compiling Pyx Files

I've just started to learn cython and this is the first time that I'm trying to compile .pyx files. I tried to run in my cmd: Cython fib.pyx which gave me my fib.c file. then I r

Solution 1:

I always compile my cython with one line of gcc:

gcc -shared -Wall -O3 -I Python27/include -L Python27/libs -o fib.so fib.c -l python27

You see, including the header files (-I) for python isn't enough. You also have to include the location of python's libraries (-L), and then the name of the file to use as that library (-l).

Happy Cythonizing!

Solution 2:

There is another solution that might come in handy with bigger projects. Instead of writing yourself the gcc call in the command line you can create a configuration file in python that cython will use to autogenerate C or C++ code and call the gcc compiler with the appropriate flags.

Simply create a file setup.py (or a filename of your preference). Then fill it with:

from distutils.coreimport setup
from distutils.extensionimportExtensionfromCython.Buildimport cythonize

ext = Extension("fib",
            sources=["fib.pyx"],
            language="c++",
            include_dirs=[],
            libraries=[],
            extra_link_args=[])

setup(ext_modules = cythonize([ext]))

Then in the terminal python setup.py build_ext --inplace.

This will generate a fib.cpp file and compile it to the shared object file fib.so as well as an object file fib.o (this last in a folder called build). After that, you can already import fib in your *.py files.

Post a Comment for "Compiling Pyx Files"