【问题标题】:Undefined Symbols with Python.hPython.h 中的未定义符号
【发布时间】:2011-07-05 05:29:28
【问题描述】:

我正在尝试将 Python 脚本嵌入到 C++ 应用程序中。不过,在我做这样的事情之前,我正在尝试运行示例脚本。

这是我的代码:

#include <Python/Python.h>
int main(int argc, char *argv[]) {
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
                   "print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}

用 g++ 编译给了我:

Undefined symbols:
  "_Py_Initialize", referenced from:
      _main in cc2Ogphq.o
  "_PyRun_SimpleStringFlags", referenced from:
      _main in cc2Ogphq.o
  "_Py_Finalize", referenced from:
      _main in cc2Ogphq.o
ld: symbol(s) not found

我正在运行 Mac OSX Snow Leopard,并且正在运行 Python 2.7.2。

【问题讨论】:

  • 你用什么命令编译的?您是否在链接器选项中包含了 python 库?
  • 我刚刚做了“g++ main.cpp”。我认为这不是正确的方法。正如你可能知道的那样,我不太会用 C++ 编程......
  • 您需要链接到 python 库以获取其符号。检查您已安装的 python 库的版本,然后通过将-lpython2.6 添加到编译命令来链接到该版本,例如。 (参考下面已经给出的答案)。
  • 非常感谢!我的示例代码现在可以工作了。

标签: c++ python python-2.7


【解决方案1】:

您需要链接到 python 库,例如libpython.a 用于静态链接。

【讨论】:

    【解决方案2】:

    这个答案陈旧而令人讨厌(静态,eww)。

    distutils 是大多数情况下的答案。

    如果你真的坚持DIY,把这个加到你的~/.profile中:

    # Works on Lion
    
    alias pygcc='gcc -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/ /usr/lib/python2.7/config/libpython2.7.dylib'
    
    alias pyg++='gcc -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/ /usr/lib/python2.7/config/libpython2.7.dylib'
    

    用法: pyg++ yourfile.cc

    pygcc someotherfile.c

    【讨论】:

      【解决方案3】:

      当然,我的回答有些迟了, 但我有一个同样的问题,我被需要 做一些搜索 我使用 ubuntu 11,bash 外壳 解决方法是:

      g++ c_pyth.cpp -o c_pyth -I /usr/include/python2.7/ /usr/lib/python2.7/config/libpython2.7.so

      如果不包含 /usr/include/python2.7/ ,编译器将看不到“Python.h”

      如果不包含 /usr/lib/python2.7/config/libpython2.7.so ,编译器将无法生成静态可执行文件

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多