CodeHelp
Posts: 2
Joined: Tue Jun 30, 2020 7:28 pm

C++ running Python Problems

Tue Jun 30, 2020 8:19 pm

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.

User avatar
PeterO
Posts: 5828
Joined: Sun Jul 22, 2012 4:14 pm

Re: C++ running Python Problems

Tue Jun 30, 2020 9:30 pm

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
Last edited by PeterO on Wed Jul 01, 2020 5:24 am, edited 1 time in total.
Discoverer of the PI2 XENON DEATH FLASH!
Interests: C,Python,PIC,Electronics,Ham Radio (G0DZB),1960s British Computers.
"The primary requirement (as we've always seen in your examples) is that the code is readable. " Dougie Lawson

CodeHelp
Posts: 2
Joined: Tue Jun 30, 2020 7:28 pm

Re: C++ running Python Problems

Tue Jun 30, 2020 10:37 pm

Thanks so much! I've got it working just fine now.

Return to “C/C++”