How to set up an environment in which a python fragment can run in a C ++ program?

I created two embed.py useEmbed.cpp in my home directory.

embed.py

 import os print os.getcwd() 

useEmbed.cpp

  #include <iostream> #include "Python.h" using namespace std; int main() { Py_Initialize(); PyRun_SimpleFile("embed.py"); Py_Finalize(); return 0; } 

The g++ useEmbed.cpp -o useEmbed returns Python.h not found . What should I do next so that the .cpp file .cpp successfully and returns the correct answer? Thanks for the tips on setting up your environment for this test.

Thanks!

UPDATE : Thanks for the advice from David and Alexander. The problem was resolved after installing the python-devel on my Fedora Linux.

+3
source share
2 answers

On linux, you can use python-config to get compiler flags (python-config -cflags) and linker flags (python-config -ldflags).

For instance:

#> python-config --cflags
-I/usr/include/python2.5 -I/usr/include/python2.5 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes

#> python-config --ldflags
-L/usr/lib/python2.5/config -lpthread -ldl -lutil -lm -lpython2.5

To compile your program, you can run g ++ useEmbed.cpp -o embed "cflags" "ldflags":

#> g++ useEmbed.cpp -o embed -I/usr/include/python2.5 -I/usr/include/python2.5 -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -L/usr/lib/python2.5/config -lpthread -ldl -lutil -lm -lpython2.5

I had to modify useEmbed.cpp a bit:

 #include "Python.h" #include <iostream> using namespace std; int main() { Py_Initialize(); FILE *file = fopen("embed.py","r+"); PyRun_SimpleFile(file,"embed.py"); Py_Finalize(); fclose(file); return 0; }
#include "Python.h" #include <iostream> using namespace std; int main() { Py_Initialize(); FILE *file = fopen("embed.py","r+"); PyRun_SimpleFile(file,"embed.py"); Py_Finalize(); fclose(file); return 0; } 
+3
source

Make sure you point the compiler to the directory where Python.h is located, i.e. use the -I<path> switch with gcc. Of course, you must install the Python development files.

+3
source

Source: https://habr.com/ru/post/1347184/


All Articles