Embedding Python in C

Marcin 'Qrczak' Kowalczyk qrczak at knm.org.pl
Wed Jun 9 13:46:47 CEST 2004

I made a bridge between my language Kogut
<http://qrnik.knm.org.pl/~qrczak/kogut/kogut.html> and Python,
which gives my language instant access to Python libraries.
(I'm only linking to libpython, I'm not using the standalone

I have a question about the proper way of compilation and linking.
Currently I do it like this:

I assume that the interpreter installed as 'python' determines the version.
I check Python version:

   if python -c 'import sys; sys.exit(not hasattr(sys, "version_info"))'; then
      ko_cv_python_major=`python -c 'import sys; print sys.version_info[0]'`

and similarly the minor version. Currently I accept only 2.2 and higher
because of language features (iterators); while I could support earlier
versions too with appropriate conditional compilation, I didn't bother.

I check Python include directory:

   ko_cv_python_include=`python -c 'from distutils import sysconfig
print sysconfig.get_python_inc()'`

I add this directory to -I options of the C compiler (currently GCC only
is supported), and #include <Python.h>.

For linking, I add
for version 2.3 and above, and
   -lpython -ldl -lpthread -lutil -lm
for earlier versions, i.e. 2.2 only.


1. How to do it better? For example I feel uneasy about the way I specify
   which libraries should be linked. Is there a way to determine it in a
   more robust way?

2. Someone has reported to me that he has no distutils installed. Why
   could it be? I thought distutils is a part of the core Python package.
   Can I rely on distutils, and if not, how to determine the include

3. I assume that -lpython is the same version as the 'python' program,
   and give no way to select alternative versions if multiple versions
   are installed. Should I do it in some better way?

   __("<         Marcin Kowalczyk
   \__/       qrczak at knm.org.pl
    ^^     http://qrnik.knm.org.pl/~qrczak/

More information about the Python-list mailing list