Compiling Your Module

After writing the enumeration you can compile your Pyrex module. There are two ways to build your module: using gcc or using distutils. Both methods have be verified to work on Linux, however Windows® users may find it easier to use distutils.

XOSD

Building Your Module Using gcc

To build your module using gcc is a three step process on Unix. Under Windows® it is easier to use distutils than to compile your module using a compiler.

  1. Start by running the Pyrex compiler over your code as follows, where mymodule.pyx is the name of the Pyrex module you are writing.
    bash$ python2.2 pyrexc mymodule.pyx
  2. Next, compile the resulting C file into a .o file. The call to gcc looks like this:

    bash$ gcc -c -fPIC -I/usr/include/python2.2/ mymodule.c

    The arguments to gcc are explained below.

    -c
    Produces a .o file instead of an executable.
    -fPIC
    Produces position independent code, so we can dynamically link against it later.
    -I/usr/include/python2.2/
    is the location of the Python 2.2 include file. The location of your Python include file may differ from /usr/include/python2.2/.
    mymodule.c
    is the name of the C file produced by Pyrex.

After creating the .so module you then import it into Python.

Building Your Module Using distutils

Instead of using the command-line (or make) to compile your modules, you may find it easier (especially on Windows®) to use distutils.

The following is a distutils setup file that compiles a Pyrex module called mymodule.

from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
  name = "PyrexGuide",
  ext_modules=[ 
    Extension("mymodule", ["mymodule.pyx"], libraries = ["xosd"])
    ],
  cmdclass = {'build_ext': build_ext}
)

Multiple modules can be added to the setup file by adding more instances of Extension classes to the ext_modules list. Save the above code in a file called setup.py and run the following code to build your module.

bash$ python2.2 setup.py build_ext --inplace

Using Your Module

After building your module, you can import the module into Python 2.2 using the import statement.

import mymodule
print dir(mymodule)