1

我想用c写一个python扩展。我在 Mac 上工作,我从这里获取了一个代码:

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

4

3 回答 3

8

两件事情:

  • 您需要将扩展​​链接为共享对象(您正在尝试链接可执行文件,这就是链接器正在寻找的原因main());
  • 您需要链接 Python 静态库 ( -lpython)。
于 2013-03-26T07:49:48.057 回答
4
  1. 使用以下命令查询 python env 路径:
$python-config --includes
-I/usr/include/python2.6 -I/usr/include/python2.6
$python-config --ldflags
-lpthread -ldl -lutil -lm -lpython2.6
  1. 生成 .o 文件:

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

  1. 生成 .so 文件:

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

于 2015-03-26T07:05:05.070 回答
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 模板取自这里

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

python-config --includes

于 2013-03-26T09:00:09.870 回答