1

I am trying to upgrade a small C module to work with Python 3.x and having trouble getting it to compile. My roadblock right now is that the preprocessor defines I am supposed to be using to check the Python version aren't working.

The module contains two .c files at the moment (I've temporarily commented out the rest). In both files, PY_MAJOR_VERSION is undefined so the compiler cannot use the Python 3.x specific definitions where needed.

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])

I am building with c:\python31\python setup.py bdist_wininst

Where is PY_MAJOR_VERSION supposed to get defined? Is it something I need to tell distutils to pass to the compiler?

1 Answer 1

8

I figured out what I was doing wrong. It's Python.h that defines PY_MAJOR_VERSION. By putting my #defines ahead of my #includes, I missed out on the definition. I don't know why I was thinking that the build system would define it for me...

Moving the #if PY_MAJOR_VERSION >= 3 so that it executes after #include "Python.h" fixes the problem. I will leave this here in case someone else is as dumb as I was, because there was nothing useful on Google for this query.

Sign up to request clarification or add additional context in comments.

3 Comments

Just going to say that. Define testing could be very easy if you are using an IDE like VS2010.
You should select your own asnwer as the answer, so the question gets marked as answered.
Done, thank you. Still learning my way around this place a bit. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.