[Tutor] embedding python in a C app on a linux box...

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Dec 7 20:18:02 CET 2004

On Tue, 7 Dec 2004, Jason Child wrote:

> Ok, so I have a decent grasp of python and have coded quite a few
> scripts. I must say that the language rocks. I would like to embed
> python into a C app to provide some scripting support.

Hi Jason,

We have to first mention that most of us here are beginning Python
programmers; few of us have done Python/C integration, so we're probably
not the best people to ask for help.  You may want to ask your
extension-building questions on comp.lang.python; I'm sure the experts
there will be happy to help you.  That being said, we'll do what we can.

> It would seem that my problem lies with not understanding the
> environment (linux) well enough. First off, I must include the Python.h
> header escplicitly (via #include "/usr/include/python2.3/Python.h"). How
> do I add the correct dir to the search path for the <> format?

This is controlled by adding a '-I/usr/include/python2.3' flag argument to
gcc, so that gcc adds that as part of its include path search.

 Second, when I call Py_Initialize() I get:
> /tmp/ccXZxNHZ.o(.text+0x11): In function `main':
> : undefined reference to `Py_Initialize'
> collect2: ld returned 1 exit status
> Now, I think it is because the linker isnt finding the right lib to
> attach. Is there a switch to use for gcc for make it? -L /path/to/libs
> perhaps?

You'll probably need '-lpython' so that it links Python to your
executable.  The uppercase '-L' flag is something else: it controls where
gcc looks for additional libraries, and I think it automatically include
'/usr/lib' by default.

You may find the stuff near the bottom of:


useful: it shows an example 'gcc' call that has all the flags that one
needs to get an extension built in Linux.

There's also an example of an embedded application that's in the Python
source tree.  It's under the Demo/embed directory, and may be a good
starting-off point.

But again, try asking your question on comp.lang.python.  I have to admit
that I haven't done embedding much, so there may be a better way to infer
those 'gcc' flags without hardcoded them in some kind of Makefile.

Good luck to you!

More information about the Tutor mailing list