The standard way to build and install C extension modules with Python is to use the features of Distutils which is included in the standard Python library. Generally that means including the C file(s) in your project directory and creating a configuration file, normally called setup.py
, to identify the C source files. By running a properly-configured setup.py
file under Python, Distutils
will take care of compiling and linking the C source files by using your system's C compiler and linker. (On OS X, you'll need to have installed Apple's free Xcode
Developer Tools which installs versions of gcc
.) Wading through all the Distutils documentation to figure out what to do can be overwhelming right now. Here's a simple tutorial that should be enough to get you started.
Why use a Distutils setup.py
rather than just calling gcc yourself? Several reasons:
Since C extensions normally run within the context of the Python interpreter itself, it is important that extensions be compiled and linked in a manner compatible with the C code in the interpreter. Distutils tries to take the guesswork out of this by supplying the right options for the Python you are executing under. This can be particularly important on OS X where Pythons come in various flavors including some with various combinations of multi-architecture executables (i.e. -arch i386
, -arch ppc
, -arch x86_64
, -arch ppc64
) and with support for multiple OS X versions (i.e. the current python.org OS X installers are compatible with OS X 10.4 through 10.6).
Distutils allows you to package up and distribute combinations of pure Python and C extension modules in a machine and operating system independent way. In many cases, if the C code is written to avoid operating system dependent system calls and the like, your C extensions can be built and installed on most current Python platforms without modification and without you having to know which C compiler to use or options to set.
You'll find that nearly all modern Python third-party packages with C code work this way so it's good to get in the habit of using Distutils for this from the start.
As you'll see in the tutorial, it's very easy to setup a setup.py
file for many cases.