Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using distutils and build_clib to build C library

Tags:

python

cython

Does anyone have a good example of using the build_clib command in distutils to build an external (non-python) C library from setup.py? The documentation on the subject seems to be sparse or non-existent.

My aim is to build a very simple external library, then build a cython wrapper which links to it. The simplest example I've found is here, but this uses a system() call to gcc which I can't imagine is best practice.

like image 746
Snorfalorpagus Avatar asked May 31 '13 09:05

Snorfalorpagus


People also ask

Is Distutils deprecated?

distutils has been deprecated in NumPy 1.23. 0 . It will be removed for Python 3.12; for Python <= 3.11 it will not be removed until 2 years after the Python 3.12 release (Oct 2025).

What does Distutils do in Python?

The distutils package provides support for building and installing additional modules into a Python installation. The new modules may be either 100%-pure Python, or may be extension modules written in C, or may be collections of Python packages which include modules coded in both Python and C.


1 Answers

Instead of passing a library name as a string, pass a tuple with the sources to compile:

setup.py

import sys
from distutils.core import setup
from distutils.command.build_clib import build_clib
from distutils.extension import Extension
from Cython.Distutils import build_ext

libhello = ('hello', {'sources': ['hello.c']})

ext_modules=[
    Extension("demo", ["demo.pyx"])
]

def main():
    setup(
        name = 'demo',
        libraries = [libhello],
        cmdclass = {'build_clib': build_clib, 'build_ext': build_ext},
        ext_modules = ext_modules
    )

if __name__ == '__main__':
    main()

hello.c

int hello(void) { return 42; }

hello.h

int hello(void);

demo.pyx

cimport demo
cpdef test():
    return hello()

demo.pxd

cdef extern from "hello.h":
    int hello()

Code is available as a gist: https://gist.github.com/snorfalorpagus/2346f9a7074b432df959

like image 124
Snorfalorpagus Avatar answered Sep 21 '22 00:09

Snorfalorpagus