2010-12-04 102 views
0

我想升級一個小的C模塊以使用Python 3.x並且無法編譯它。我現在的障礙是預處理器定義了我應該用來檢查Python版本無效。PY_MAJOR_VERSION在爲Python 3.x編譯Python C模塊時未定義

該模塊目前包含兩個.c文件(我暫時將其餘部分註釋掉了)。在這兩個文件中,PY_MAJOR_VERSION都是未定義的,因此編譯器無法在需要的地方使用Python 3.x特定的定義。

mymodule.c的:

#ifndef PY_MAJOR_VERSION 
#error Major version not defined! 
#endif 

#if PY_MAJOR_VERSION >= 3 
#define PY3K 
#endif 

#include "Python.h" 
#include "myobj.h" 

/* omitted: irrelevant boilerplate structs */ 

PyMODINIT_FUNC 
initmymodule(void) 
{ 
    PyObject* m; 

#ifdef PY3K 
    m = PyModule_Create(&mymodule_struct); 
#else 
    (void) Py_InitModule("mymodule", MyModMethods); 
    m = Py_InitModule3("mymodule", NULL, 
       "My Module"); 
#endif 

    /* omitted: the rest of the module init code */ 
} 

myobj.c:

#ifndef PY_MAJOR_VERSION 
#error Major version not defined! 
#endif 

#if PY_MAJOR_VERSION >= 3 
#define PY3K 
#endif 

#include "Python.h" 
#define NEED_STATIC 
#include "myobj.h" 
#undef NEED_STATIC 

#ifdef PY3K 
#define PYSTR_FROMC PyUnicode_FromString 
#define PYSTR_FORMAT PyUnicode_Format 
#define PYINT_FROMC PyLong_FromLong 
#else 
#define PYSTR_FROMC PyString_FromString 
#define PYSTR_FORMAT PyString_Format 
#define PYINT_FROMC PyInt_FromLong 
#endif 

/* omitted: rest of module code */ 

setup.py:

from distutils.core import setup, Extension 

module1 = Extension('mymodule', sources = ['mymodule.c', 'myobj.c']) 
setup(name='mymodule', version='0.1', ext_modules=[module1]) 

我與c:\python31\python setup.py bdist_wininst

建築物是PY_MAJOR_VERSION蘇想要定義?是否需要告訴distutils傳遞給編譯器?

回答

4

我弄清楚我做錯了什麼。它是Python.h,它定義了PY_MAJOR_VERSION。通過將#define放在我的#includes之前,我錯過了定義。我不知道爲什麼我認爲構建系統會爲我定義它...

移動#if PY_MAJOR_VERSION> = 3,以便它在#include「Python.h」中修復問題後執行。如果有人像我一樣愚蠢,我會在此留下此處,因爲Google對此查詢沒有任何用處。

+0

只是要說。如果您使用的是像VS2010這樣的IDE,定義測試可能非常容易。 – Kabie 2010-12-04 09:47:10