Using distutils and build_clib to build C library

前端 未结 1 1453
误落风尘
误落风尘 2021-02-12 20:56

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 sub

1条回答
  •  终归单人心
    2021-02-12 21:40

    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

    0 讨论(0)
提交回复
热议问题