Entry
Embedding Python code in a C++ program, I get dynamic linking errors if I try to import any non-built in module, what's wrong?
Jul 26th, 2000 05:53
unknown unknown, Ted Drain
Problem:
I am trying to learn how to embed Python code in a C++ program. I got
the example from the docs (the one that imports sys and prints out a
couple of strings -- search from initxyzzy in google). The problem I get
is that if I try to import any non-built in module, I get dynamic
linking errors. For example, adding the following line 31 works:
_______________________________________________________________________
...
29 /* Execute some Python statements (in module __main__)
*/
30 PyRun_SimpleString("import sys\n");
--> 31 PyRun_SimpleString("import thread\n");
32 PyRun_SimpleString("print sys.builtin_module_names\n");
...
_______________________________________________________________________
but adding the following line instead:
_______________________________________________________________________
...
29 /* Execute some Python statements (in module __main__)
*/
30 PyRun_SimpleString("import sys\n");
--> 31 PyRun_SimpleString("import random\n");
32 PyRun_SimpleString("print sys.builtin_module_names\n");
...
_______________________________________________________________________
produces:
_______________________________________________________________________
[lopes@groucho lopes]$ ./demo
Hello, brave new world
Traceback (innermost last):
File "<string>", line 1, in ?
File "/usr/lib/python1.5/random.py", line 22, in ?
import whrandom
File "/usr/lib/python1.5/whrandom.py", line 140, in ?
_inst = whrandom()
File "/usr/lib/python1.5/whrandom.py", line 46, in __init__
self.seed(x, y, z)
File "/usr/lib/python1.5/whrandom.py", line 58, in seed
import time
ImportError: /usr/lib/python1.5/lib-dynload/timemodule.so: undefined
symbol: PyExc_IOError
('__builtin__', '__main__', 'imp', 'marshal', 'pcre', 'posix', 'regex',
'signal', 'sys', 'thread')
['xyzzy', 'os.path', 'os', 'exceptions', '__main__', 'posix',
'whrandom', 'sys', '__builtin__', 'site', 'random', 'signal',
'UserDict', 'posixpath', 'stat']
./demo
['./demo']
_______________________________________________________________________
Solution:
If you're building w/ gcc, add the link line option:
-Wl,-E
This says to pass the -E option to the linker. This option tells the
linker to make all statically linked symbols available to the dynamic
libraries. Without it, the symbols linked from libpython1.5.a aren't
seen by symbols in the dynamic libraries.