链接器错误与PyList_New

Linker error with PyList_New

本文关键字:New PyList 错误 链接      更新时间:2023-10-16

当我遇到此错误时,我正在尝试在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。

我找到了一个答案:如果你使用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