C 用Python.h编译未定义的符号

C++ Compiling with Python.h Undefined Symbols

本文关键字:未定义 符号 编译 Python      更新时间:2023-10-16

所以,我一直在尝试使用Python.h进行我想从事的小项目,看起来很漂亮/很简单。但是在开始之前,我想尝试学习如何使用python.h。所以我在网上找到了这个小示例。

#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);  
}

似乎很简单。当我第一次使用

gcc test.cpp

要编译,我得到了一些未定义的符号。我很快发现我应该使用

-lpython2.7

然后我发现我也可以使用

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

不起作用(我确保存在/library/frameworks/python/versions/2.7/lib/存在)我卡住了,我该怎么办?我得到

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

编辑:我只是尝试使用-framework参数,并尝试在-l -l python2.7参数之后添加,然后我得到

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

现在什么?

如果您在OS X上使用Python Framework安装,因为它看起来是基于路径,则可以将-framework参数用于Apple Compiler驱动程序:

cc test.cpp -framework Python

另外,您可以明确指定目录路径和库名:

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

更新:通过在注释中报告的配置(Xcode 3.2.6gcc-4.2),似乎您需要明确调用gccc++变体。两者:

g++ test.cpp -framework Python

c++ test.cpp -framework Python

应该工作。