2017-10-17 50 views
1

我試圖建立用C Python模塊,並停留在一個問題:定製的C模塊包括

當我包括額外的頭文件(test.h),模塊編譯沒有警告,但後來import這個模塊,Python抱怨未定義的符號maketest

我的模塊結構如下(模塊被命名爲spam):

內容的 spammodule.c
spam\ 
    ├spammodule.c 
    |setup.py 
    ├─src\ 
     |── test.c 
     |── test.h 

#include <Python.h> 
#include "test.h" 

static PyObject * SpamError; 

static PyObject * 
spam_system(PyObject *self, PyObject *args) 
{ 
    const char *command; 
    int sts; 

    maketest(); // <---- calling function from additional file 

    if(!PyArg_ParseTuple(args, "s", &command)) 
     return NULL; 

    sts = system(command); 
    if (sts < 0) { 
     PyErr_SetString(SpamError, "System command failed"); 
     return NULL; 
    } 
    return PyLong_FromLong(sts); 
} 

PyMODINIT_FUNC 
initspam(void) 
{ 
    PyObject *m; 
    static PyMethodDef SpamMethods[] = { 
     {"system", spam_system, METH_VARARGS, "Execute a shell command."}, 
     {NULL, NULL, 0, NULL} 
    }; 
    m = Py_InitModule("spam", SpamMethods); 
    if (m == NULL) 
     return; 

    SpamError = PyErr_NewException("spam.error", NULL, NULL); 
    Py_INCREF(SpamError); 
    PyModule_AddObject(m, "error", SpamError); 
} 

int 
main(int argc, char *argv[]) 
{ 
    Py_SetProgramName(argv[0]); 
    Py_Initialize(); 
    initspam(); 
} 

setupy.py內容:中src/test.h

from setuptools import setup,Extension 

spam_module = Extension('spam', 
     sources = ['spammodule.c'], 
     include_dirs=['src/'],) 

setup (name = 'Spam', 
    version = '1.0', 
    description = 'Sample module.', 
    ext_modules = [ spam_module ]) 

內容:

void maketest(void); 

src/test.c內容:

#include "test.h" 

void maketest() { 
    printf("test passed"); 
} 

我編譯一切與python setup.py build,運行Python提示符我試圖導入我的模塊,並且得到錯誤後:

Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
[GCC 5.2.1 20151010] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import spam 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
ImportError: ./spam.so: undefined symbol: maketest 

是否有人有線索怎麼回事?

+1

你絕對無法將src/test.c的目標文件鏈接到'.so'中。將'src/test.c'添加到源列表中。 –

+0

你說得對,我認爲包括'src/*'文件已經足夠了,但是沒有,正如你所說的其他文件應該列在源元組中,謝謝。我在我的帖子後添加了答案 – user3459276

+0

不,你應該*發佈*你的答案作爲*答案*。然後*接受它*! –

回答

0

確定球員感謝Antii爲線索,你說的問題是test.c的應包含在源元組 所以我修改setup.py,一切工作正常 現在look`s這樣的:

from setuptools import setup,Extension 

spam_module = Extension('spam', 
     sources = ['spammodule.c','src/test.c'], 
     include_dirs=['src/']) 

setup (name = 'Spam', 
    version = '1.0', 
    description = 'Sample module.', 
    ext_modules = [ spam_module ])