Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the environment in which python snippet can run in c++ program?

Tags:

c++

python

I have created two files embed.py useEmbed.cppin 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;
  }

Command g++ useEmbed.cpp -o useEmbed returns Python.h not found, What should i do next step to make .cpp file compiled successfully and return the right answer? Thank for tips about how to set environment to make this test OK.

Thank you!

UPDATE: Thanks for tips from David and Alexander. Problem has been solved after install package python-devel in my Fedora Linux.

like image 394
Jason Avatar asked Nov 01 '25 17:11

Jason


1 Answers

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

For example:

#> 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 change useEmbed.cpp a little 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;
    }


like image 134
David L. Avatar answered Nov 03 '25 06:11

David L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!