I'm using the example in python's 2.6 docs to begin a foray into embedding some python in C. The example C-code does not allow me to execute the following 1 line script:
import math
Using line:
./tmp.exe tmp foo bar
it complains
Traceback (most recent call last):
File "/home/rbroger1/scripts/tmp.py", line 1, in
import math
ImportError: [...]/python/2.6.2/lib/python2.6/lib-dynload/math.so: undefined symbol: PyInt_FromLong
When I do nm on my generated binary (tmp.exe) it shows
0000000000420d30 T PyInt_FromLong
The function seems to be defined, so why can't the shared object find the function?
解决方案
I'm using Python 2.6, and I successfully compiled and ran that same example code that you listed, without changing anything in the source.
$ gcc python.c -I/usr/include/python2.6/ /usr/lib/libpython2.6.so
$ ./a.out random randint 1 100
Result of call: 39
$ ./a.out random randint 1 100
Result of call: 57
I specifically chose the random module because it does have from math import log,... so it is certainly importing the math module as well.
Your issue is probably due to how you're linking; see this forum post for a similar issue someone else had. I can't find the links again, but it seems like there are some common issues when trying to link against Python's static library then importing modules that require a dynamic library.