distutils cygwinccompiler provides the cygwinccompiler class a subclass of unixccompiler that handles the cygwin port of the gnu c compiler to windows it also contains the mingw32ccompiler class which handles the mingw32 port of gcc same as cygwin in nocygwin mode problems if you use a msvc compiled python version 1 5 2 1 you have to insert a gnuc section in its config h 2 you have to generate an import library for its dll create a deffile for python dll create an import library using dlltool dllname python15 dll def python15 def outputlib libpython15 a see also http starship python netcrewkernrmingw32notes html we put exportsymbols in a deffile and don t use exportallsymbols because it doesn t worked reliable in some tested configurations and because other windows compilers also need their symbols specified this no serious problem tested configurations cygwin gcc 2 91 57ld 2 9 4dllwrap 0 2 4 works after patching python s config h and for c some other include files see also http starship python netcrewkernrmingw32notes html mingw32 gcc 2 95 2ld 2 9 4dllwrap 0 2 4 works ld doesn t support shared so we use dllwrap cygwin gcc 2 95 2ld 2 10 90dllwrap 2 10 90 works now its dllwrap doesn t work there is a bug in binutils 2 10 90 see also http sources redhat commlcygwin200006msg01274 html using gcc mdll instead dllwrap doesn t work without static because it tries to link against dlls instead their import libraries if it finds the dll first by specifying static we force ld to link against the import libraries this is windows standard and there are normally not the necessary symbols in the dlls only the version of june 2000 shows these problems cygwin gcc 3 2ld 2 13 90 works ld supports shared mingw gcc 3 2ld 2 13 works ld supports shared include the appropriate msvc runtime library if python was built with msvc 7 0 or later msvc 7 0 msvc 7 1 vs2005 msvc 8 0 vs2008 msvc 9 0 vs2010 msvc 10 0 handles the cygwin port of the gnu c compiler to windows ldversion 2 10 90 and 2 13 should also be able to use gcc mdll instead of dllwrap older dllwraps had own version numbers newer ones use the same as the rest of binutils also ld dllwrap 2 10 90 is buggy ldversion 2 13 support shared so use it instead of mdll static hardcode gcc because that s what this is all about xxx optimization warnings etc should be customizable cygwin and mingw32 need different sets of libraries cygwin shouldn t need msvcrt but without the dlls will crash gcc version 2 91 57 perhaps something about initialization include the appropriate msvc runtime library if python was built with msvc 7 0 or later the same as cygwin plus some additional parameters handles the mingw32 port of the gnu c compiler to windows ldversion 2 13 support shared so use it instead of mdll static a real mingw32 doesn t need to specify a different entry point but cygwin 2 91 57 in nocygwinmode needs it maybe we should also append mthreads but then the finished dlls need another dll mingwm10 dll see mingw32 docs mthreads support threadsafe exception handling on mingw32 no additional libraries needed include the appropriate msvc runtime library if python was built with msvc 7 0 or later because these compilers aren t configured in python s pyconfig h file by default we should at least warn the user if he is using an unmodified version check if the current python installation appears amenable to building extensions with gcc returns a tuple status details where status is one of the following constants confighok all is well go ahead and compile confighnotok doesn t look good confighuncertain not sure unable to read pyconfig h details is a humanreadable string explaining the situation note there are two ways to conclude ok either sys version contains the string gcc implying that this python was built with gcc or the installed pyconfig h contains the string gnuc xxx since this function also checks sys version it s not strictly a pyconfig h check should probably be renamed if sys version contains gcc then python was compiled with gcc and the pyconfig h file should be ok let s see if gnuc is mentioned in python h find the version of an executable by running cmd in the shell if the command is not found or the output does not match reversion returns none looseversion works with strings so we need to decode our bytes try to find out the versions of gcc ld and dllwrap if not possible it returns none for it try to determine if the gcc that would be used is from cygwin outstring checkoutput gcc dumpmachine return outstring strip endswithb cygwin problems if you use a msvc compiled python version 1 5 2 1 you have to insert a __gnuc__ section in its config h 2 you have to generate an import library for its dll create a def file for python dll create an import library using dlltool dllname python15 dll def python15 def output lib libpython15 a see also http starship python net crew kernr mingw32 notes html we put export_symbols in a def file and don t use export all symbols because it doesn t worked reliable in some tested configurations and because other windows compilers also need their symbols specified this no serious problem tested configurations cygwin gcc 2 91 57 ld 2 9 4 dllwrap 0 2 4 works after patching python s config h and for c some other include files see also http starship python net crew kernr mingw32 notes html mingw32 gcc 2 95 2 ld 2 9 4 dllwrap 0 2 4 works ld doesn t support shared so we use dllwrap cygwin gcc 2 95 2 ld 2 10 90 dllwrap 2 10 90 works now its dllwrap doesn t work there is a bug in binutils 2 10 90 see also http sources redhat com ml cygwin 2000 06 msg01274 html using gcc mdll instead dllwrap doesn t work without static because it tries to link against dlls instead their import libraries if it finds the dll first by specifying static we force ld to link against the import libraries this is windows standard and there are normally not the necessary symbols in the dlls only the version of june 2000 shows these problems cygwin gcc 3 2 ld 2 13 90 works ld supports shared mingw gcc 3 2 ld 2 13 works ld supports shared include the appropriate msvc runtime library if python was built with msvc 7 0 or later msvc 7 0 msvc 7 1 vs2005 msvc 8 0 vs2008 msvc 9 0 vs2010 msvc 10 0 handles the cygwin port of the gnu c compiler to windows ld_version 2 10 90 and 2 13 should also be able to use gcc mdll instead of dllwrap older dllwraps had own version numbers newer ones use the same as the rest of binutils also ld dllwrap 2 10 90 is buggy ld_version 2 13 support shared so use it instead of mdll static hard code gcc because that s what this is all about xxx optimization warnings etc should be customizable cygwin and mingw32 need different sets of libraries cygwin shouldn t need msvcrt but without the dlls will crash gcc version 2 91 57 perhaps something about initialization include the appropriate msvc runtime library if python was built with msvc 7 0 or later the same as cygwin plus some additional parameters handles the mingw32 port of the gnu c compiler to windows ld_version 2 13 support shared so use it instead of mdll static a real mingw32 doesn t need to specify a different entry point but cygwin 2 91 57 in no cygwin mode needs it maybe we should also append mthreads but then the finished dlls need another dll mingwm10 dll see mingw32 docs mthreads support thread safe exception handling on mingw32 no additional libraries needed include the appropriate msvc runtime library if python was built with msvc 7 0 or later because these compilers aren t configured in python s pyconfig h file by default we should at least warn the user if he is using an unmodified version check if the current python installation appears amenable to building extensions with gcc returns a tuple status details where status is one of the following constants config_h_ok all is well go ahead and compile config_h_notok doesn t look good config_h_uncertain not sure unable to read pyconfig h details is a human readable string explaining the situation note there are two ways to conclude ok either sys version contains the string gcc implying that this python was built with gcc or the installed pyconfig h contains the string __gnuc__ xxx since this function also checks sys version it s not strictly a pyconfig h check should probably be renamed if sys version contains gcc then python was compiled with gcc and the pyconfig h file should be ok let s see if __gnuc__ is mentioned in python h find the version of an executable by running cmd in the shell if the command is not found or the output does not match re_version returns none looseversion works with strings so we need to decode our bytes try to find out the versions of gcc ld and dllwrap if not possible it returns none for it try to determine if the gcc that would be used is from cygwin
import sys
from subprocess import Popen, PIPE, check_output
import re

from distutils.unixccompiler import UnixCCompiler
from distutils.errors import CCompilerError
from distutils.version import LooseVersion
from distutils.spawn import find_executable

def get_msvcr():
    
    msc_pos = sys.version.find('MSC v.')
    if msc_pos != -1:
        msc_ver = sys.version[msc_pos+6:msc_pos+10]
        if msc_ver == '1300':
            
            return ['msvcr70']
        elif msc_ver == '1310':
            
            return ['msvcr71']
        elif msc_ver == '1400':
            
            return ['msvcr80']
        elif msc_ver == '1500':
            
            return ['msvcr90']
        elif msc_ver == '1600':
            
            return ['msvcr100']
        else:
            raise ValueError("Unknown MS Compiler version %s " % msc_ver)


class CygwinCCompiler(UnixCCompiler):
    
    compiler_type = 'cygwin'
    obj_extension = ".o"
    static_lib_extension = ".a"
    shared_lib_extension = ".dll"
    static_lib_format = "lib%s%s"
    shared_lib_format = "%s%s"
    exe_extension = ".exe"

    def __init__(self, verbose=0, dry_run=0, force=0):

        UnixCCompiler.__init__(self, verbose, dry_run, force)

        status, details = check_config_h()
        self.debug_print("Python's GCC status: %s (details: %s)" %
                         (status, details))
        if status is not CONFIG_H_OK:
            self.warn(
                "Python's pyconfig.h doesn't seem to support your compiler. "
                "Reason: %s. "
                "Compiling may fail because of undefined preprocessor macros."
                % details)

        self.gcc_version, self.ld_version, self.dllwrap_version = \
            get_versions()
        self.debug_print(self.compiler_type + ": gcc %s, ld %s, dllwrap %s\n" %
                         (self.gcc_version,
                          self.ld_version,
                          self.dllwrap_version) )

        
        
        
        
        
        if self.ld_version >= "2.10.90":
            self.linker_dll = "gcc"
        else:
            self.linker_dll = "dllwrap"

        
        
        if self.ld_version >= "2.13":
            shared_option = "-shared"
        else:
            shared_option = "-mdll -static"

        
        
        self.set_executables(compiler='gcc -mcygwin -O -Wall',
                             compiler_so='gcc -mcygwin -mdll -O -Wall',
                             compiler_cxx='g++ -mcygwin -O -Wall',
                             linker_exe='gcc -mcygwin',
                             linker_so=('%s -mcygwin %s' %
                                        (self.linker_dll, shared_option)))

        
        if self.gcc_version == "2.91.57":
            
            
            self.dll_libraries=["msvcrt"]
            self.warn(
                "Consider upgrading to a newer version of gcc")
        else:
            
            
            self.dll_libraries = get_msvcr()



class Mingw32CCompiler(CygwinCCompiler):
    
    compiler_type = 'mingw32'

    def __init__(self, verbose=0, dry_run=0, force=0):

        CygwinCCompiler.__init__ (self, verbose, dry_run, force)

        
        
        if self.ld_version >= "2.13":
            shared_option = "-shared"
        else:
            shared_option = "-mdll -static"

        
        
        if self.gcc_version <= "2.91.57":
            entry_point = '--entry _DllMain@12'
        else:
            entry_point = ''

        if is_cygwingcc():
            raise CCompilerError(
                'Cygwin gcc cannot be used with --compiler=mingw32')

        self.set_executables(compiler='gcc -O -Wall',
                             compiler_so='gcc -mdll -O -Wall',
                             compiler_cxx='g++ -O -Wall',
                             linker_exe='gcc',
                             linker_so='%s %s %s'
                                        % (self.linker_dll, shared_option,
                                           entry_point))
        
        
        

        
        self.dll_libraries=[]

        
        
        self.dll_libraries = get_msvcr()





CONFIG_H_OK = "ok"
CONFIG_H_NOTOK = "not ok"
CONFIG_H_UNCERTAIN = "uncertain"

def check_config_h():
    

    
    

    import sysconfig

    
    
    if "GCC" in sys.version:
        return CONFIG_H_OK, "sys.version mentions 'GCC'"

    
    fn = sysconfig.get_config_h_filename()
    try:
        config_h = open(fn)
        try:
            if "__GNUC__" in config_h.read():
                return CONFIG_H_OK, "'%s' mentions '__GNUC__'" % fn
            else:
                return CONFIG_H_NOTOK, "'%s' does not mention '__GNUC__'" % fn
        finally:
            config_h.close()
    except OSError as exc:
        return (CONFIG_H_UNCERTAIN,
                "couldn't read '%s': %s" % (fn, exc.strerror))

RE_VERSION = re.compile(br'(\d+\.\d+(\.\d+)*)')

def _find_exe_version(cmd):
    
    executable = cmd.split()[0]
    if find_executable(executable) is None:
        return None
    out = Popen(cmd, shell=True, stdout=PIPE).stdout
    try:
        out_string = out.read()
    finally:
        out.close()
    result = RE_VERSION.search(out_string)
    if result is None:
        return None
    
    
    return LooseVersion(result.group(1).decode())

def get_versions():
    
    commands = ['gcc -dumpversion', 'ld -v', 'dllwrap --version']
    return tuple([_find_exe_version(cmd) for cmd in commands])

def is_cygwingcc():
    
    out_string = check_output(['gcc', '-dumpmachine'])
    return out_string.strip().endswith(b'cygwin')