2013-03-26 73 views
1

我想在c中編寫一個python擴展。我在Mac上工作,我參加了一個代碼herePython擴展:找不到架構x86_64錯誤的符號

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

回答

7

兩件事情:

  • 您需要將擴展​​爲一個共享對象(你試圖鏈接的可執行文件,這就是爲什麼連接正在尋找main())鏈接;
  • 您需要鏈接到Python靜態庫(-lpython)。
+0

其中靜態蟒LIB可以找到? – 0x90 2013-03-26 07:55:24

+0

取決於您的操作系統和Python安裝。在我的盒子裏,它在'/ usr/lib'中(實際上,對於不同版本的Python,有一大堆庫)。 – NPE 2013-03-26 07:57:49

+0

我沒有找到一個python靜態庫'find/-iname * libpython * 2>&1 | grep -v「^ find」'only'.dylib'和'.a'文件 – 0x90 2013-03-26 08:21:43

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 [email protected] $< $(CFLAGS) 

py_module: $(OBJ) 
     gcc -shared $^ $(CFLAGS) -I$(LIBS_DIR) $(LIBS) -o [email protected] 

.PHONY: clean 

clean: 
     rm -f $(ODIR)/*.o *~ core $(INCDIR)/*~ 

生成文件的模板已經從here拍攝。

爲了找到的路徑中,可以使用python-config --ldflags

python-config --includes

+1

如果您執行了'CFLAGS = $(shell python-config --cflags)',則不需要'-I $(LIBS_DIR)',除此之外您可以執行'LDFLAGS = $ shell python-config --ldflags)',並通過'gcc -shared $^$(LDFLAGS)-o $ @'來使用它。 – glglgl 2013-03-26 09:41:32

+0

@glglgl幾乎已經足夠好了,除了'python-config''的輸出沒有提供完整的路徑。請參閱http://stackoverflow.com/questions/15634863/possible-bug-in-python-config – 0x90 2013-03-26 10:35:22

2
  1. 查詢與這些命令蟒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

    1. 生成.so文件:

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

    相關問題