使用 Python.h undefined symbol 的 C++ 编译

标签 c++ python gcc python-2.7

所以,我一直在尝试开始使用 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

为了编译,我得到了一些 undefined symbol 。我很快发现我应该使用

-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 框架安装,则可以使用 Apple 编译器驱动程序的 -framework 参数:

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),看来您需要显式调用c++ gcc 的变体。要么:

g++ test.cpp -framework Python

c++ test.cpp -framework Python

应该可以。

关于使用 Python.h undefined symbol 的 C++ 编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13115988/

相关文章:

c++ - 函数原型(prototype)中的不同参数名称

python - 路径名中的编码字符

c - C中参数的默认数据类型?

c++ - 匿名命名空间中的 const 与 static const

c++ - 为什么未命名的命名空间是静态的 "superior"替代品?

c++ - 强制类模板特化以提供一种或多种方法

python - CondaValueError : The target prefix is the base prefix. 正在中止

python - 如何选择 sqlite3 数据库的所有行,这些行的列中包含某个变量子字符串?

c++11 - DSO 库符号似乎具有默认可见性,但应该是隐藏的

c - printf 和 long double