5

I'm working on embedding Python in some C++ code, but I'm getting stuck compiling it.

For a header file, I have

#include <Python.h>

I would initial try,

$g++ EmbeddedPython.cpp

but would end up getting

EmbeddedPython.cpp:1:20: error: Python.h: No such file or directory
EmbeddedPython.cpp: In function ‘int main(int, char**)’:
EmbeddedPython.cpp:6: error: ‘Py_Initialize’ was not declared in this scope
....

I then tried

g++ EmbeddedPython.cpp -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5

and that got rid of the first two errors, but I still ended up with

 Undefined symbols:
  "_Py_Initialize", referenced from:
  _main in ccxJAUAB.o

I'm a bit of new to this, but I think I'm learning fast. I believe I need to 'Link' a library, right? But which one and how? Do I need a dynamic or a static one?

I am working on a MacBook Pro.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
csta
  • 2,423
  • 5
  • 26
  • 34

1 Answers1

5

You need to link against libpython. UNIX programmers do this with "-lpython" in the link command (ie at the end of that "g++" command). On a Mac, I think it would be "-framework Python".

aksommerville
  • 358
  • 1
  • 5
  • That worked thanks. Is there something else I can type so that I don't have to type -I/System/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 – csta Jul 01 '11 at 23:19
  • I don't know exactly what Apple's gcc does with frameworks. If "-framework Python" didn't take care of that, then I think you're stuck with what you have there. – aksommerville Jul 01 '11 at 23:23
  • For newer versions of python it should be "-lpythonX.Y" where X.Y is the python version. For example, for python 3.8 it should be "-lpython3.8". – ibci Jan 17 '22 at 11:17