PDA

Archiv verlassen und diese Seite im Standarddesign anzeigen : embedded python, undefined reference to `Py_Initialize'



newton
06-08-2004, 09:44
Hi,
ich möchte aus einem C++ Prgramm python benutzten.
Also beispielsweise:


#include <iostream>
#include "/usr/include/python2.2/Python.h"

int main(int argc, char * argv[])
{
// initialize the interpreter
Py_Initialize();

// evaluate some code
PyRun_SimpleString("import sys\n");
//ignore line wrap on following line
PyRun_SimpleString("sys.stdout.write('Hello from an embedded Python Script\n')\n");
// shut down the interpreter
Py_Finalize();
return 0;
}


Wenn ich das jetzt kompiliere (auf Redhat 9), bekomm ich folgende Meldung:

/tmp/ccuSgVFb.o(.text+0x11): In function `main':
: undefined reference to `Py_Initialize'
/tmp/ccuSgVFb.o(.text+0x1e): In function `main':
: undefined reference to `PyRun_SimpleString'
/tmp/ccuSgVFb.o(.text+0x2e): In function `main':
: undefined reference to `PyRun_SimpleString'
/tmp/ccuSgVFb.o(.text+0x36): In function `main':
: undefined reference to `Py_Finalize'
collect2: ld returned 1 exit status


Wenn ichs richtig versteh, dann weis der compiler nichts mit den Py* funktionen anzufangen, aber eigentlich sollten die doch in Python.h definiert sein. :confused:
Weis jemand Rat/Abhilfe ?

Gruss,
newton

newton
11-08-2004, 15:28
Hi,
hier die lösung des Problems, wie ich sie von meinem Onkel erfahren habe:


I needed to do the following:

(1) In the C++ source file, I changed the

PyRun_SimpleString("sys.stdout.write('Hello from an embedded Python Script\n')\n");

to

PyRun_SimpleString("sys.stdout.write('Hello from an embedded Python Script\\n')\n");

(Note the doubled \ before the first n. The C++ compiler turns
that into a single \, so that Python winds up with \n. With
just one \, the C++ compiler would turn \n into a newline
character, which Python chokes on.)

(2) Having put this modified program in foo.cpp, I then compiled on linux with

g++ -o foo foo.cpp /usr/lib/python2.2/config/libpython2.2.a -ldl -lpthread -lutil -lm

This includes not only the python library I mentioned in my
previous email [ /usr/lib/python2.2/config/libpython2.2.a], but also various standard libraries (for dynamic
loading, concurrent threads, utilities, and math) that Python
seems to rely on.

An equivalent compiler line that would be more consistent in how
it mentions the python library (the same way as the standard
libraries) would be

g++ -o foo foo.cpp -L/usr/lib/python2.2/config -lpython2.2 -ldl -lpthread -lutil -lm

The -L option gives another directory to look in for the
libraries that the -l option then abbreiviates.

This compilation gave a few warnings, but no errors.

(3) Then I was able to run the program as

./foo

and get the expected output.




sollte jemand an einer deutschen version intresse haben, bitte posten :)

gruss,
newton