Search code examples
cythonsetuptoolsdistutils

Use distutils setuptools for compile and link


I want to compile and link some cython (and cython_freeze) generated c files into an executable (on Windows and Linux)

I can do this by setting up (a machine specifc) environment (eg what C compiler, where is it installed (path), what include directories, what lib directories...) and calling cl directly (with some os specific options).

But cythonize is is able to compile cython created c files into dynamic libraries without me explicitly setting any machine or os specific settings (just using distutils).

Is there a simple way of using distutils / setuptools to do that (ie compile a c file into a object and link multiple objects into a executable)?

NB: I don't want any of the complex setup logic normally in setup.py. Just the plain compile and link primitives for my development machines.


Solution

  • There is a quite simple solution (that is not really documented):

    import sys
    import sysconfig
    
    #from distutils.ccompiler import new_compiler  # distutils is currently deprecated
    from setuptools._distutils.ccompiler import new_compiler
    
    compiler = new_compiler()
    compiler.add_include_dir(sysconfig.get_path("include"))
    compiler.add_library_dir(sysconfig.get_config_var("installed_platbase") + "/libs")
    
    if sys.platform == "linux":
        compiler.add_library_dir(sysconfig.get_config_var("LIBPL"))
        compiler.add_library_dir(sysconfig.get_config_var("LIBDIR"))
    
        compiler.add_library(sysconfig.get_config_var("LIBRARY")[3:-2])
        for lib in sysconfig.get_config_var("LIBS").split():
            compiler.add_library(lib[2:])
    
    objectFiles = compiler.compile(["source1.c", "source2.c", "test.rc"])
    compiler.link_executable(objectFiles, "test")