首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >编译Python 3.x的Python C模块时PY_MAJOR_VERSION未定义

问编译Python 3.x的Python C模块时PY_MAJOR_VERSION未定义
EN

Stack Overflow用户
提问于 2010-12-04 17:28:16
回答 1查看 1.7K关注 0票数 0

我正在尝试升级一个小的C模块来使用Python3.x,但在编译它时遇到了问题。我现在遇到的障碍是,我应该用来检查Python版本的预处理器定义不起作用。

该模块目前包含两个.c文件(我暂时注释掉了其余的文件)。在这两个文件中,PY_MAJOR_VERSION都是未定义的,因此编译器无法在需要的地方使用Python3.x特定的定义。

mymodule.c:

代码语言:javascript
复制
#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:

代码语言:javascript
复制
#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:

代码语言:javascript
复制
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传递给编译器的东西吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-12-04 17:42:24

我发现我做错了什么。定义PY_MAJOR_VERSION的是Python.h。通过把我的#定义放在我的#包含之前,我错过了定义。我不知道为什么我会认为构建系统会为我定义它...

将#if PY_MAJOR_VERSION >= 3移到#include "Python.h“之后执行可以解决这个问题。我将把这个留在这里,以防其他人像我一样愚蠢,因为Google上没有任何有用的东西来处理这个查询。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4352847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档