Python扩展:找不到架构x86_64错误的符号
我想在c中写一个python扩展。 我在Mac上工作,我从这里拿了一个代码:
#include static PyObject* say_hello(PyObject* self, PyObject* args) { const char* name; if (!PyArg_ParseTuple(args, "s", &name)) return NULL; printf("Hello %s!\n", name); Py_RETURN_NONE; } static PyMethodDef HelloMethods[] = { {"say_hello", say_hello, METH_VARARGS, "Greet somebody."}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inithello(void) { (void) Py_InitModule("hello", HelloMethods); }
我编译它:
gcc -c -o py_module.o py_module.c -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/ gcc -o py_module py_module.o -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/ -lm
但我得到这个错误:
Undefined symbols for architecture x86_64: "_PyArg_ParseTuple", referenced from: _say_hello in py_module.o "_Py_InitModule4_64", referenced from: _inithello in py_module.o "__Py_NoneStruct", referenced from: _say_hello in py_module.o "_main", referenced from: start in crt1.10.6.o ld: symbol(s) not found for architecture x86_64 collect2: ld returned 1 exit status make: *** [py_module] Error 1
为什么python不支持X86_64
架构?
两件事情:
- 您需要将扩展名链接为共享对象(您尝试链接可执行文件,这就是链接器查找
main()
); - 您需要链接Python静态库(
-lpython
)。
- 使用以下命令查询python env路径:
$python-config --includes -I/usr/include/python2.6 -I/usr/include/python2.6 $python-config --ldflags -lpthread -ldl -lutil -lm -lpython2.6
- 生成.o文件:
$ g ++ -fPIC -c -I / usr / include / python2.6 -I / usr / include / python2.6 xx.cpp
- 生成.so文件:
g ++ -shared xx.o -o xx.so
感谢@NPE @glglgl和anatoly这里是我的Makefile:
DIR=/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7/ CC=gcc CFLAGS=-I$(DIR) ODIR=. LIBS_DIR=/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config/ LIBS=-lpython2.7 _DEPS = DEPS = $(patsubst %,$(IDIR)/%,$(_DEPS)) _OBJ = py_module.o OBJ = $(patsubst %,$(ODIR)/%,$(_OBJ)) $(ODIR)/%.o: %.c $(DEPS) $(CC) -c -o $@ $< $(CFLAGS) py_module: $(OBJ) gcc -shared $^ $(CFLAGS) -I$(LIBS_DIR) $(LIBS) -o $@ .PHONY: clean clean: rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~
makefile模板已从这里获取 。
为了找到路径,可以使用python-config --ldflags
和python-config --includes