3.3.3 Preprocessor options

Three optional arguments to Extension will help if you need to specify include directories to search or preprocessor macros to define/undefine: include_dirs, define_macros, and undef_macros.

For example, if your extension requires header files in the include directory under your distribution root, use the include_dirs option:

Extension("foo", ["foo.c"], include_dirs=["include"])

You can specify absolute directories there; if you know that your extension will only be built on Unix systems with X11R6 installed to /usr, you can get away with

Extension("foo", ["foo.c"], include_dirs=["/usr/include/X11"])
You should avoid this sort of non-portable usage if you plan to distribute your code: it's probably better to write your code to include (e.g.) <X11/Xlib.h>.

If you need to include header files from some other Python extension, you can take advantage of the fact that the Distutils install extension header files in a consistent way. For example, the Numerical Python header files are installed (on a standard Unix installation) to /usr/local/include/python1.5/Numerical. (The exact location will differ according to your platform and Python installation.) Since the Python include directory--/usr/local/include/python1.5 in this case--is always included in the search path when building Python extensions, the best approach is to include (e.g.) <Numerical/arrayobject.h>. If you insist on putting the Numerical include directory right into your header search path, though, you can find that directory using the Distutils sysconfig module:

from distutils.sysconfig import get_python_inc
incdir = os.path.join(get_python_inc(plat_specific=1), "Numerical")
setup(...,
      Extension(..., include_dirs=[incdir]))
Even though this is quite portable--it will work on any Python installation, regardless of platform--it's probably easier to just write your C code in the sensible way.

You can define and undefine pre-processor macros with the define_macros and undef_macros options. define_macros takes a list of (name, value) tuples, where name is the name of the macro to define (a string) and value is its value: either a string or None. (Defining a macro FOO to None is the equivalent of a bare #define FOO in your C source: with most compilers, this sets FOO to the string 1.) undef_macros is just a list of macros to undefine.

For example:

Extension(...,
          define_macros=[('NDEBUG', '1')],
                         ('HAVE_STRFTIME', None),
          undef_macros=['HAVE_FOO', 'HAVE_BAR'])
is the equivalent of having this at the top of every C source file:
#define NDEBUG 1
#define HAVE_STRFTIME
#undef HAVE_FOO
#undef HAVE_BAR


See About this document... for information on suggesting changes.