Page 1 of 1

C++ running Python Problems

Posted: Tue Jun 30, 2020 8:19 pm
by CodeHelp
First, sorry if this is the wrong place, I'm a beginner to Raspberry Pi and C++ and Python. I'm trying to do the tutorial here: https://www.codeproject.com/Articles/82 ... splus-code , but I keep getting errors (I'm using Geany). The program will compile just fine, but when I build I get runtime errors. I've searched extensively for an answer and have found everything from python problems to alternate build commands, but cannot figure it out for the life of me. Any help is much appreciated.

PyTest.cpp

Code: Select all

#include </usr/include/python3.7/Python.h>

int main(){

Py_Initialize();
PyRun_SimpleString("print('it Worked')");
Py_Finalize();

return 0;
}
Error Messages

Code: Select all

g++ -Wall -o "PyTest" "PyTest.cpp" -lm -ldl -lpthread -pthread (in directory: /home/pi/Desktop/CtoPython)
/usr/bin/ld: /tmp/cc1X5N10.o: in function `main':
PyTest.cpp:(.text+0x14): undefined reference to `Py_Initialize'
/usr/bin/ld: PyTest.cpp:(.text+0x20): undefined reference to `PyRun_SimpleStringFlags'
/usr/bin/ld: PyTest.cpp:(.text+0x24): undefined reference to `Py_Finalize'
collect2: error: ld returned 1 exit status
Compilation failed.

Re: C++ running Python Problems

Posted: Tue Jun 30, 2020 9:30 pm
by PeterO
It looks like you aren't linking the appropriate library....

Here's how I found out....

Code: Select all

$ pkg-config --list-all | grep Python
python              Python - Python library
python-3.7m         Python - Python library
python-3.7          Python - Python library
python2             Python - Python library
python3             Python - Python library
python-2.7          Python - Python library
$ gcc -o t t.c $(pkg-config --cflags --libs python3)
$ ./t
it Worked
$
Also the #include line shouldn't have the full path in it

Code: Select all

#include <Python.h>

int main(){

Py_Initialize();
PyRun_SimpleString("print('it Worked')");
Py_Finalize();

return 0;
}
You need to add the include paths given by "pkg-config --cflags python3" to your geany project and add the library given by "pkg-config --libs python3" to the librarys to link.

PeterO

Re: C++ running Python Problems

Posted: Tue Jun 30, 2020 10:37 pm
by CodeHelp
Thanks so much! I've got it working just fine now.