Posted on Nov 19, 2007

How to do conditional includes in Pyrex

When trying to get Rabbyt to build on MacOS, I ran into a slight problem. On most systems, you include the OpenGL header files from GL/gl.h and GL/glu.h. But on MacOS, you have to include gl.h and glu.h. No buts.

In C I would think, "big deal. Just use #ifdef __APPLE__ and be done with it." Only, Pyrex works a little different. At the time there was no conditional compiling, and even now the conditional compiling features don't work too well for includes.

Naturally, I overcomplicated the problem. I built into my setup script a routine that processes the C files after Pyrex is done with them, doing the corrections that I needed. It was an ungly hack, but it technically got the job done. And so long as I didn't look at the setup script I was happy.

But then I wanted to add MSVC support. I would have to include windows.h before including GL/gl.h, redefine some math functions, among other things. Uhg.

I'm writing this in case if anyone else makes the same stupid mistake. The solution is incredibly simple. Just put all of your conditional includes in a separate .h file!

Here's one that I named include_gl.h:

#ifdef _MSC_VER
#include <windows.h>
#endif

#ifdef __APPLE__
#include <gl.h>
#include <glu.h>
#else
#include <GL/gl.h>
#include <GL/glu.h>
#endif

With that, things are made incredibly simple!

cdef extern from "include_gl.h":
    cdef int GL_SMOOTH
    ...

Duh.