linking with shared library, undefined reference to Py_BuildValue

Erwin S. Andreasen erwin at andreasen.com
Thu Mar 6 11:49:09 EST 2003


jkpangtang at yahoo.com (JW) writes:

> I have 2 files:
> 1) spam.c
> int gcd(int x, int y)

> 2) spamwrapper.c
> #include "Python.h"
> 
> extern int gcd(int, int);
> extern void print_data(char *, char *, char *);
> 
> PyObject* spam_gcd(PyObject *self, PyObject *args)

> When i try compiling and linking main.c with spammodule.so and libpython2.2.a,
> i get the following error messages:
> -->./spammodule.so - undefined reference 'Py_BuildValue'
> --> ./spammodule.so - undefined reference 'Py_InitModule4'

Why do you want to link the Python part of your module if you are
going to call only the plain C method directly? I'd suggest compiling
spam.c to spam.so separately if that's all you want to do.

Your undefined reference however is caused by the linker discarding
all of libpython2.2.a. When you link with a *static* library (which is
really a collection of .o files with an index) the linker will decide
on a .o file basis whether that .o file is really needed -- and it
does that based what unsatisfied undefind references are pending so
far. If nothing needs that .o file inside the .a, it is not linked in.

Since nothing in your program needs anything in libpython2.2.a, no
part of it actually gets included into your main program.

With a real appliation that embeds Python, you woud call various
Python interpreter initiliazation functions, as described in
http://www.python.org/doc/current/ext/embedding.html -- this would
pull in the necessary Python functions from the library.

If you absolutely want to force inclusion of the .a file in its
entirety (which would be a waste if you aren't actually going to embed
Python), you can use the GNU ld --whole-archive option:

$ gcc -rdynamic test.c -o test  -Wl,--whole-archive /usr/lib/python2.2/config/libpython2.2.a  -Wl,--no-whole-archive -lutil -lm -ldl -lpthread

$ ls -la test
-rwxr-xr-x    1 erwin    users      899268 Mar  6 17:45 test


. or use a shared libpython2.2, if available. Don't forget the
-rdynamic option, as Martin mentioned.


-- 
===============================================================
<erwin at andreasen.org>                           Herlev, Denmark     
<URL:http://www.andreasen.org/>                             <*>   
===============================================================





More information about the Python-list mailing list