Python扩展:找不到架构x86_64错误的符号

时间:2013-03-26 07:48:09

标签: python c python-2.7

我想在c中编写一个python扩展。我在Mac上工作,我从here获取代码:

#include <Python.h>

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架构?

3 个答案:

答案 0 :(得分:7)

两件事:

  • 您需要将扩展​​名链接为共享对象(您尝试链接可执行文件,这就是链接器正在寻找main());
  • 您需要链接Python静态库(-lpython)。

答案 1 :(得分:2)

  1. 使用以下命令查询python env路径:
  2. $python-config --includes
    -I/usr/include/python2.6 -I/usr/include/python2.6
    $python-config --ldflags
    -lpthread -ldl -lutil -lm -lpython2.6
    
    1. 生成.o文件:
    2.   

      $ g ++ -fPIC -c -I / usr / include / python2.6 -I / usr / include / python2.6 xx.cpp

      1. 生成.so文件:
      2.   

        g ++ -shared xx.o -o xx.so

答案 2 :(得分:1)

感谢@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模板取自here

为了找到路径,可以使用python-config --ldflags

python-config --includes