[Distutils] C extension modules

David Cournapeau cournape at gmail.com
Wed Jan 27 02:57:37 CET 2010


On Wed, Jan 27, 2010 at 2:30 AM, Torsten Mohr <tmohr at s.netic.de> wrote:

>
> What is the preferred way to make this information available to the compiler
> so i can use code like #ifdef HOST_posix?

Use a config.h, like autoconf does. Distutils does not make it for
you, and plugging the necessary code in distutils to do it is a PITA,
but that's doable.

Basically, you need to extend the distutils config command, and goes from there:

import sys
from distutils.core import setup
from distutils.command.config import config

def generate_config_h(filename, defs):
    with open(filename, "w") as fid:
        fid.write("#ifndef HAVE_CONFIG_H\n")
        fid.write("#define HAVE_CONFIG_H\n\n")

        for d in defs:
            if isinstance(d, str):
                fid.write("#define %s\n" % d)
            else:
                fid.write("#define %s %s\n" % (d[0], d[1]))
        fid.write("\n#endif\n")

class MyConfig(config):
    def check_headers(self, headers=None):
        if headers is None:
            headers = []

        body = """\
/* Some stupid comment because distutils does not accept empty body */
"""
        return self.try_compile(body, headers)

    def run(self):
        defines = []
        if self.check_headers(["stdio.h"]):
            defines.append(("HAVE_STDIO_H", 1))
        if self.check_headers(["stdlib.h"]):
            defines.append(("HAVE_STDLIB_H", 1))

        if sys.platform == "win32":
            defines.append(("FOO_OS_WIN32", 1))
        else:
            defines.append(("FOO_OS_POSIX", 1))
        generate_config_h("config.h", defines)

setup(name="yo", cmdclass={"config": MyConfig})

Once config is run by distutils, you end up with a config.h that you
will then import in your extensions. The fun starts when you need to
deal with build directories and the like,

cheers,

David


More information about the Distutils-SIG mailing list