C++ Compiling with Python.h Undefined Symbols-Collection of common programming errors

So, I’ve been trying to start using Python.h for a little project I want to work on that seems pretty /simple/. But before I start I want to try to learn how to use Python.h. So I found this little example online.

#include "Python/Python.h"  

int main(int argc, char** argv)  
{  
    Py_Initialize();  
    PyRun_SimpleString("print 'Test'");  
    PyRun_SimpleString("print str(3 + 5)"); 
    Py_Exit(0);  
}

Seems pretty straight forward. When i first used

gcc test.cpp

to compile, i got some undefined symbols. I quickly found out I should use

-lpython2.7

then I found out I could also use

-L/Library/Frameworks/Python.framework/Versions/2.7/lib/

that didn’t work (I made sure that /Library/Frameworks/Python/Versions/2.7/lib/ existed) I’m stuck, what do I do? I get

Undefined symbols:
  "_Py_Initialize", referenced from:
      _main in ccoUOSlc.o
  "_PyRun_SimpleStringFlags", referenced from:
      _main in ccoUOSlc.o
      _main in ccoUOSlc.o
  "___gxx_personality_v0", referenced from:
      _main in ccoUOSlc.o
      CIE in ccoUOSlc.o
  "_Py_Exit", referenced from:
      _main in ccoUOSlc.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

EDIT: I just tried using the -Framework argument, and tried adding after the -L the -l python2.7 argument, and I now get

Undefined symbols:
  "___gxx_personality_v0", referenced from:
      _main in ccfvtJ4j.o
      CIE in ccfvtJ4j.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

Now what?

  1. If you are using an Python framework installation on OS X as it appears you are based on the paths, you can use the -framework argument to the Apple compiler drivers:

    cc test.cpp -framework Python
    

    Alternatively, you can explicitly specify the directory path and library name:

    cc test.cpp -L /Library/Frameworks/Python.framework/Versions/2.7/lib/ -l python2.7
    

    Update: With the configuration you report in the comments (Xcode 3.2.6, gcc-4.2), it appears you need to explicitly invoke the c++ variant of gcc. Either:

    g++ test.cpp -framework Python
    

    or

    c++ test.cpp -framework Python
    

    should work.

Originally posted 2013-11-09 22:59:17.