【问题标题】:Linker error with PyList_NewPyList_New 的链接器错误
【发布时间】:2018-08-16 18:45:21
【问题描述】:

当我遇到这个错误时,我试图在 python 脚本中使用 C 函数:

Undefined symbols for architecture x86_64:
  "_PyList_Append", referenced from:
      _count_arr in mi1-5e9b85.o
  "_PyList_New", referenced from:
      _count_arr in mi1-5e9b85.o
  "_Py_BuildValue", referenced from:
      _count_arr in mi1-5e9b85.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

.cpp 文件为:

#include <cstring>
#include <iostream>
//#include <Python.h>
#include "/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/include/python3.6m/Python.h"
#include <vector>

#ifdef __cplusplus
extern "C" PyObject* count_arr(char** arr, unsigned n2, char* word)
#else
PyObject* count_arr(char** arr, unsigned n2, char* word)
#endif
{
    PyObject * PList = PyList_New(0);
    vector <int> intVector;
    for(unsigned j = 0; j < n2; j++)
    {
        if(strstr(arr[j], word) != NULL) {intVector.push_back(j);}
    }
    vector<int>::const_iterator it;
    for(it = intVector.begin(); it != intVector.end() ; it++ )
    {
        PyList_Append(PList, Py_BuildValue("i", *it));
    }
    return PList;
}

如果我尝试包含 Python.h,我会收到有关缺少此标头的消息。操作系统是macos。

【问题讨论】:

  • 你需要包含 Python.h。如果这给您一个错误,您需要传递一个 -I 和 Python 标头的路径。您还需要使用-l 将Python 库传递给链接器,如果这给您带来错误,您还需要带有Python 库路径的-L。这一切都应该在嵌入和扩展文档中进行解释,但它还需要一些 C++ 和使用 clang 的基本知识,您可能也缺少这些知识。

标签: python c++ python-3.x macos


【解决方案1】:

我找到了答案:如果你使用clang,你需要传递类似的东西

clang mi.o -I/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/include -lpython3.6 -L /usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib

但是,如果你使用g++,你需要使用命令

g++ -fPIC -c mi1.cpp -o mi.o -I/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/include/python3.6m/
g++ -shared -lpython3.6 -L /usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib -olibmi.so mi.o

【讨论】:

    猜你喜欢
    • 2016-08-01
    • 2015-08-18
    • 2010-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多