Cross compiling Python applications for Windows with the Linux mingw32 compiler

With this guide, you will be able to generate a .exe binary Windows installer for your Python applications - even if you have C extension modules that need to be compiled.

1. Cross compiling Python for Windows on Linux

The patches below combine the two Python SourceForge patches #1006238: cross compile patch and #841454: Cross building python for mingw32. No external software (ie scons) or a local python build (it is built from the source itself) is needed.

Files to download:

How to compile:

  1. Make a CVS checkout:
    cvs -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/python login
    and then either
    cvs -z3 -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/python co python
    for Python 2.4 or
    cvs -z3 -d:pserver:anonymous@cvs.sourceforge.net:/cvsroot/python co -r release23-maint python
    for Python 2.3
  2. Patch the source with one of the according patches above.
  3. Copy autogen.sh in python/dist/src/ and execute it.
  4. Copy crossbuild.sh in python/dist/src/ and execute it. The paths to the mingw compiler commands are absolute, you might have to adjust them.

You have now a python.exe (you don't need it, but it works in Wine :) and a cross-compiled-for-windows library libpythonX.Y.a (this is what we wanted).

2. Using distutils bdist_wininst on Linux

The generation of an .exe installer is now not very hard. You have to set the CC, CXX, LDSHARED and PY_BUILD_PLATFORM environment variables to point to your mingw compiler and start setup.py. The paths to the mingw compiler commands are absolute, you might have to adjust them.

CC=/usr/bin/i586-mingw32msvc-gcc \
  CCSHARED=/usr/bin/i586-mingw32msvc-gcc \
  CXX=/usr/bin/i586-mingw32msvc-g++ \
  LDSHARED="/usr/bin/i586-mingw32msvc-gcc -shared" \
  PY_HOST_PLATFORM="nt" \
  python setup.py build -c mingw32 bdist_wininst

A complete setup.py example demonstrates what your application has to do to support cross compiling.
Your setup.py has to detect that it is cross compiling and adjust some defines or macros accordingly. Necessary are includes to the cross compiled directory, and the linker flags for the cross compiled library libpythonX.Y.a. Plus you have to disable the builtin safety catch of bdist_wininst against cross compiling by subclassing bdist_wininst.

3. Enjoy

Thats it. Windows is no more needed for calling bdist_wininst :)