build_ext.py revision 95b1cf646a8a2a82ce7e45213361dd0506e42f72
1"""distutils.command.build_ext
2
3Implements the Distutils 'build_ext' command, for building extension
4modules (currently limited to C extensions, should accommodate C++
5extensions ASAP)."""
6
7__revision__ = "$Id$"
8
9import sys, os, re
10from site import USER_BASE, USER_SITE
11from distutils.core import Command
12from distutils.errors import *
13from distutils.sysconfig import customize_compiler, get_python_version
14from distutils.dep_util import newer_group
15from distutils.extension import Extension
16from distutils.util import get_platform
17from distutils import log
18
19if os.name == 'nt':
20    from distutils.msvccompiler import get_build_version
21    MSVC_VERSION = int(get_build_version())
22
23# An extension name is just a dot-separated list of Python NAMEs (ie.
24# the same as a fully-qualified module name).
25extension_name_re = re.compile \
26    (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
27
28
29def show_compilers ():
30    from distutils.ccompiler import show_compilers
31    show_compilers()
32
33
34class build_ext(Command):
35
36    description = "build C/C++ extensions (compile/link to build directory)"
37
38    # XXX thoughts on how to deal with complex command-line options like
39    # these, i.e. how to make it so fancy_getopt can suck them off the
40    # command line and make it look like setup.py defined the appropriate
41    # lists of tuples of what-have-you.
42    #   - each command needs a callback to process its command-line options
43    #   - Command.__init__() needs access to its share of the whole
44    #     command line (must ultimately come from
45    #     Distribution.parse_command_line())
46    #   - it then calls the current command class' option-parsing
47    #     callback to deal with weird options like -D, which have to
48    #     parse the option text and churn out some custom data
49    #     structure
50    #   - that data structure (in this case, a list of 2-tuples)
51    #     will then be present in the command object by the time
52    #     we get to finalize_options() (i.e. the constructor
53    #     takes care of both command-line and client options
54    #     in between initialize_options() and finalize_options())
55
56    sep_by = " (separated by '%s')" % os.pathsep
57    user_options = [
58        ('build-lib=', 'b',
59         "directory for compiled extension modules"),
60        ('build-temp=', 't',
61         "directory for temporary files (build by-products)"),
62        ('plat-name=', 'p',
63         "platform name to cross-compile for, if supported "
64         "(default: %s)" % get_platform()),
65        ('inplace', 'i',
66         "ignore build-lib and put compiled extensions into the source " +
67         "directory alongside your pure Python modules"),
68        ('include-dirs=', 'I',
69         "list of directories to search for header files" + sep_by),
70        ('define=', 'D',
71         "C preprocessor macros to define"),
72        ('undef=', 'U',
73         "C preprocessor macros to undefine"),
74        ('libraries=', 'l',
75         "external C libraries to link with"),
76        ('library-dirs=', 'L',
77         "directories to search for external C libraries" + sep_by),
78        ('rpath=', 'R',
79         "directories to search for shared C libraries at runtime"),
80        ('link-objects=', 'O',
81         "extra explicit link objects to include in the link"),
82        ('debug', 'g',
83         "compile/link with debugging information"),
84        ('force', 'f',
85         "forcibly build everything (ignore file timestamps)"),
86        ('compiler=', 'c',
87         "specify the compiler type"),
88        ('swig-cpp', None,
89         "make SWIG create C++ files (default is C)"),
90        ('swig-opts=', None,
91         "list of SWIG command line options"),
92        ('swig=', None,
93         "path to the SWIG executable"),
94        ('user', None,
95         "add user include, library and rpath"),
96        ]
97
98    boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
99
100    help_options = [
101        ('help-compiler', None,
102         "list available compilers", show_compilers),
103        ]
104
105    def initialize_options(self):
106        self.extensions = None
107        self.build_lib = None
108        self.plat_name = None
109        self.build_temp = None
110        self.inplace = 0
111        self.package = None
112
113        self.include_dirs = None
114        self.define = None
115        self.undef = None
116        self.libraries = None
117        self.library_dirs = None
118        self.rpath = None
119        self.link_objects = None
120        self.debug = None
121        self.force = None
122        self.compiler = None
123        self.swig = None
124        self.swig_cpp = None
125        self.swig_opts = None
126        self.user = None
127
128    def finalize_options(self):
129        from distutils import sysconfig
130
131        self.set_undefined_options('build',
132                                   ('build_lib', 'build_lib'),
133                                   ('build_temp', 'build_temp'),
134                                   ('compiler', 'compiler'),
135                                   ('debug', 'debug'),
136                                   ('force', 'force'),
137                                   ('plat_name', 'plat_name'),
138                                   )
139
140        if self.package is None:
141            self.package = self.distribution.ext_package
142
143        self.extensions = self.distribution.ext_modules
144
145        # Make sure Python's include directories (for Python.h, pyconfig.h,
146        # etc.) are in the include search path.
147        py_include = sysconfig.get_python_inc()
148        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
149        if self.include_dirs is None:
150            self.include_dirs = self.distribution.include_dirs or []
151        if isinstance(self.include_dirs, str):
152            self.include_dirs = self.include_dirs.split(os.pathsep)
153
154        # Put the Python "system" include dir at the end, so that
155        # any local include dirs take precedence.
156        self.include_dirs.append(py_include)
157        if plat_py_include != py_include:
158            self.include_dirs.append(plat_py_include)
159
160        if isinstance(self.libraries, str):
161            self.libraries = [self.libraries]
162
163        # Life is easier if we're not forever checking for None, so
164        # simplify these options to empty lists if unset
165        if self.libraries is None:
166            self.libraries = []
167        if self.library_dirs is None:
168            self.library_dirs = []
169        elif isinstance(self.library_dirs, str):
170            self.library_dirs = self.library_dirs.split(os.pathsep)
171
172        if self.rpath is None:
173            self.rpath = []
174        elif isinstance(self.rpath, str):
175            self.rpath = self.rpath.split(os.pathsep)
176
177        # for extensions under windows use different directories
178        # for Release and Debug builds.
179        # also Python's library directory must be appended to library_dirs
180        if os.name == 'nt':
181            # the 'libs' directory is for binary installs - we assume that
182            # must be the *native* platform.  But we don't really support
183            # cross-compiling via a binary install anyway, so we let it go.
184            self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
185            if self.debug:
186                self.build_temp = os.path.join(self.build_temp, "Debug")
187            else:
188                self.build_temp = os.path.join(self.build_temp, "Release")
189
190            # Append the source distribution include and library directories,
191            # this allows distutils on windows to work in the source tree
192            self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC'))
193            if MSVC_VERSION == 9:
194                # Use the .lib files for the correct architecture
195                if self.plat_name == 'win32':
196                    suffix = ''
197                else:
198                    # win-amd64 or win-ia64
199                    suffix = self.plat_name[4:]
200                new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
201                if suffix:
202                    new_lib = os.path.join(new_lib, suffix)
203                self.library_dirs.append(new_lib)
204
205            elif MSVC_VERSION == 8:
206                self.library_dirs.append(os.path.join(sys.exec_prefix,
207                                         'PC', 'VS8.0', 'win32release'))
208            elif MSVC_VERSION == 7:
209                self.library_dirs.append(os.path.join(sys.exec_prefix,
210                                         'PC', 'VS7.1'))
211            else:
212                self.library_dirs.append(os.path.join(sys.exec_prefix,
213                                         'PC', 'VC6'))
214
215        # OS/2 (EMX) doesn't support Debug vs Release builds, but has the
216        # import libraries in its "Config" subdirectory
217        if os.name == 'os2':
218            self.library_dirs.append(os.path.join(sys.exec_prefix, 'Config'))
219
220        # for extensions under Cygwin and AtheOS Python's library directory must be
221        # appended to library_dirs
222        if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
223            if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
224                # building third party extensions
225                self.library_dirs.append(os.path.join(sys.prefix, "lib",
226                                                      "python" + get_python_version(),
227                                                      "config"))
228            else:
229                # building python standard extensions
230                self.library_dirs.append('.')
231
232        # for extensions under Linux with a shared Python library,
233        # Python's library directory must be appended to library_dirs
234        if (sys.platform.startswith('linux') or sys.platform.startswith('gnu')) \
235                and sysconfig.get_config_var('Py_ENABLE_SHARED'):
236            if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
237                # building third party extensions
238                self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
239            else:
240                # building python standard extensions
241                self.library_dirs.append('.')
242
243        # The argument parsing will result in self.define being a string, but
244        # it has to be a list of 2-tuples.  All the preprocessor symbols
245        # specified by the 'define' option will be set to '1'.  Multiple
246        # symbols can be separated with commas.
247
248        if self.define:
249            defines = self.define.split(',')
250            self.define = [(symbol, '1') for symbol in defines]
251
252        # The option for macros to undefine is also a string from the
253        # option parsing, but has to be a list.  Multiple symbols can also
254        # be separated with commas here.
255        if self.undef:
256            self.undef = self.undef.split(',')
257
258        if self.swig_opts is None:
259            self.swig_opts = []
260        else:
261            self.swig_opts = self.swig_opts.split(' ')
262
263        # Finally add the user include and library directories if requested
264        if self.user:
265            user_include = os.path.join(USER_BASE, "include")
266            user_lib = os.path.join(USER_BASE, "lib")
267            if os.path.isdir(user_include):
268                self.include_dirs.append(user_include)
269            if os.path.isdir(user_lib):
270                self.library_dirs.append(user_lib)
271                self.rpath.append(user_lib)
272
273    def run(self):
274        from distutils.ccompiler import new_compiler
275
276        # 'self.extensions', as supplied by setup.py, is a list of
277        # Extension instances.  See the documentation for Extension (in
278        # distutils.extension) for details.
279        #
280        # For backwards compatibility with Distutils 0.8.2 and earlier, we
281        # also allow the 'extensions' list to be a list of tuples:
282        #    (ext_name, build_info)
283        # where build_info is a dictionary containing everything that
284        # Extension instances do except the name, with a few things being
285        # differently named.  We convert these 2-tuples to Extension
286        # instances as needed.
287
288        if not self.extensions:
289            return
290
291        # If we were asked to build any C/C++ libraries, make sure that the
292        # directory where we put them is in the library search path for
293        # linking extensions.
294        if self.distribution.has_c_libraries():
295            build_clib = self.get_finalized_command('build_clib')
296            self.libraries.extend(build_clib.get_library_names() or [])
297            self.library_dirs.append(build_clib.build_clib)
298
299        # Setup the CCompiler object that we'll use to do all the
300        # compiling and linking
301        self.compiler = new_compiler(compiler=self.compiler,
302                                     verbose=self.verbose,
303                                     dry_run=self.dry_run,
304                                     force=self.force)
305        customize_compiler(self.compiler)
306        # If we are cross-compiling, init the compiler now (if we are not
307        # cross-compiling, init would not hurt, but people may rely on
308        # late initialization of compiler even if they shouldn't...)
309        if os.name == 'nt' and self.plat_name != get_platform():
310            self.compiler.initialize(self.plat_name)
311
312        # And make sure that any compile/link-related options (which might
313        # come from the command-line or from the setup script) are set in
314        # that CCompiler object -- that way, they automatically apply to
315        # all compiling and linking done here.
316        if self.include_dirs is not None:
317            self.compiler.set_include_dirs(self.include_dirs)
318        if self.define is not None:
319            # 'define' option is a list of (name,value) tuples
320            for (name,value) in self.define:
321                self.compiler.define_macro(name, value)
322        if self.undef is not None:
323            for macro in self.undef:
324                self.compiler.undefine_macro(macro)
325        if self.libraries is not None:
326            self.compiler.set_libraries(self.libraries)
327        if self.library_dirs is not None:
328            self.compiler.set_library_dirs(self.library_dirs)
329        if self.rpath is not None:
330            self.compiler.set_runtime_library_dirs(self.rpath)
331        if self.link_objects is not None:
332            self.compiler.set_link_objects(self.link_objects)
333
334        # Now actually compile and link everything.
335        self.build_extensions()
336
337    def check_extensions_list(self, extensions):
338        """Ensure that the list of extensions (presumably provided as a
339        command option 'extensions') is valid, i.e. it is a list of
340        Extension objects.  We also support the old-style list of 2-tuples,
341        where the tuples are (ext_name, build_info), which are converted to
342        Extension instances here.
343
344        Raise DistutilsSetupError if the structure is invalid anywhere;
345        just returns otherwise.
346        """
347        if not isinstance(extensions, list):
348            raise DistutilsSetupError(
349                  "'ext_modules' option must be a list of Extension instances")
350
351        for i, ext in enumerate(extensions):
352            if isinstance(ext, Extension):
353                continue                # OK! (assume type-checking done
354                                        # by Extension constructor)
355
356            (ext_name, build_info) = ext
357            log.warn("old-style (ext_name, build_info) tuple found in "
358                     "ext_modules for extension '%s'"
359                     "-- please convert to Extension instance" % ext_name)
360            if not isinstance(ext, tuple) and len(ext) != 2:
361                raise DistutilsSetupError(
362                       "each element of 'ext_modules' option must be an "
363                       "Extension instance or 2-tuple")
364
365            if not (isinstance(ext_name, str) and
366                    extension_name_re.match(ext_name)):
367                raise DistutilsSetupError(
368                       "first element of each tuple in 'ext_modules' "
369                       "must be the extension name (a string)")
370
371            if not instance(build_info, DictionaryType):
372                raise DistutilsSetupError(
373                       "second element of each tuple in 'ext_modules' "
374                       "must be a dictionary (build info)")
375
376            # OK, the (ext_name, build_info) dict is type-safe: convert it
377            # to an Extension instance.
378            ext = Extension(ext_name, build_info['sources'])
379
380            # Easy stuff: one-to-one mapping from dict elements to
381            # instance attributes.
382            for key in ('include_dirs',
383                        'library_dirs',
384                        'libraries',
385                        'extra_objects',
386                        'extra_compile_args',
387                        'extra_link_args'):
388                val = build_info.get(key)
389                if val is not None:
390                    setattr(ext, key, val)
391
392            # Medium-easy stuff: same syntax/semantics, different names.
393            ext.runtime_library_dirs = build_info.get('rpath')
394            if 'def_file' in build_info:
395                log.warn("'def_file' element of build info dict "
396                         "no longer supported")
397
398            # Non-trivial stuff: 'macros' split into 'define_macros'
399            # and 'undef_macros'.
400            macros = build_info.get('macros')
401            if macros:
402                ext.define_macros = []
403                ext.undef_macros = []
404                for macro in macros:
405                    if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
406                        raise DistutilsSetupError(
407                              "'macros' element of build info dict "
408                              "must be 1- or 2-tuple")
409                    if len(macro) == 1:
410                        ext.undef_macros.append(macro[0])
411                    elif len(macro) == 2:
412                        ext.define_macros.append(macro)
413
414            extensions[i] = ext
415
416    def get_source_files(self):
417        self.check_extensions_list(self.extensions)
418        filenames = []
419
420        # Wouldn't it be neat if we knew the names of header files too...
421        for ext in self.extensions:
422            filenames.extend(ext.sources)
423        return filenames
424
425    def get_outputs(self):
426        # Sanity check the 'extensions' list -- can't assume this is being
427        # done in the same run as a 'build_extensions()' call (in fact, we
428        # can probably assume that it *isn't*!).
429        self.check_extensions_list(self.extensions)
430
431        # And build the list of output (built) filenames.  Note that this
432        # ignores the 'inplace' flag, and assumes everything goes in the
433        # "build" tree.
434        outputs = []
435        for ext in self.extensions:
436            fullname = self.get_ext_fullname(ext.name)
437            outputs.append(os.path.join(self.build_lib,
438                                        self.get_ext_filename(fullname)))
439        return outputs
440
441    def build_extensions(self):
442        # First, sanity-check the 'extensions' list
443        self.check_extensions_list(self.extensions)
444
445        for ext in self.extensions:
446            self.build_extension(ext)
447
448    def build_extension(self, ext):
449        sources = ext.sources
450        if sources is None or not isinstance(sources, (list, tuple)):
451            raise DistutilsSetupError(
452                  "in 'ext_modules' option (extension '%s'), "
453                  "'sources' must be present and must be "
454                  "a list of source filenames" % ext.name)
455        sources = list(sources)
456
457        fullname = self.get_ext_fullname(ext.name)
458        if self.inplace:
459            # ignore build-lib -- put the compiled extension into
460            # the source tree along with pure Python modules
461
462            modpath = fullname.split('.')
463            package = '.'.join(modpath[0:-1])
464            base = modpath[-1]
465
466            build_py = self.get_finalized_command('build_py')
467            package_dir = build_py.get_package_dir(package)
468            ext_filename = os.path.join(package_dir,
469                                        self.get_ext_filename(base))
470        else:
471            ext_filename = os.path.join(self.build_lib,
472                                        self.get_ext_filename(fullname))
473        depends = sources + ext.depends
474        if not (self.force or newer_group(depends, ext_filename, 'newer')):
475            log.debug("skipping '%s' extension (up-to-date)", ext.name)
476            return
477        else:
478            log.info("building '%s' extension", ext.name)
479
480        # First, scan the sources for SWIG definition files (.i), run
481        # SWIG on 'em to create .c files, and modify the sources list
482        # accordingly.
483        sources = self.swig_sources(sources, ext)
484
485        # Next, compile the source code to object files.
486
487        # XXX not honouring 'define_macros' or 'undef_macros' -- the
488        # CCompiler API needs to change to accommodate this, and I
489        # want to do one thing at a time!
490
491        # Two possible sources for extra compiler arguments:
492        #   - 'extra_compile_args' in Extension object
493        #   - CFLAGS environment variable (not particularly
494        #     elegant, but people seem to expect it and I
495        #     guess it's useful)
496        # The environment variable should take precedence, and
497        # any sensible compiler will give precedence to later
498        # command line args.  Hence we combine them in order:
499        extra_args = ext.extra_compile_args or []
500
501        macros = ext.define_macros[:]
502        for undef in ext.undef_macros:
503            macros.append((undef,))
504
505        objects = self.compiler.compile(sources,
506                                        output_dir=self.build_temp,
507                                        macros=macros,
508                                        include_dirs=ext.include_dirs,
509                                        debug=self.debug,
510                                        extra_postargs=extra_args,
511                                        depends=ext.depends)
512
513        # XXX -- this is a Vile HACK!
514        #
515        # The setup.py script for Python on Unix needs to be able to
516        # get this list so it can perform all the clean up needed to
517        # avoid keeping object files around when cleaning out a failed
518        # build of an extension module.  Since Distutils does not
519        # track dependencies, we have to get rid of intermediates to
520        # ensure all the intermediates will be properly re-built.
521        #
522        self._built_objects = objects[:]
523
524        # Now link the object files together into a "shared object" --
525        # of course, first we have to figure out all the other things
526        # that go into the mix.
527        if ext.extra_objects:
528            objects.extend(ext.extra_objects)
529        extra_args = ext.extra_link_args or []
530
531        # Detect target language, if not provided
532        language = ext.language or self.compiler.detect_language(sources)
533
534        self.compiler.link_shared_object(
535            objects, ext_filename,
536            libraries=self.get_libraries(ext),
537            library_dirs=ext.library_dirs,
538            runtime_library_dirs=ext.runtime_library_dirs,
539            extra_postargs=extra_args,
540            export_symbols=self.get_export_symbols(ext),
541            debug=self.debug,
542            build_temp=self.build_temp,
543            target_lang=language)
544
545    def swig_sources(self, sources, extension):
546        """Walk the list of source files in 'sources', looking for SWIG
547        interface (.i) files.  Run SWIG on all that are found, and
548        return a modified 'sources' list with SWIG source files replaced
549        by the generated C (or C++) files.
550        """
551        new_sources = []
552        swig_sources = []
553        swig_targets = {}
554
555        # XXX this drops generated C/C++ files into the source tree, which
556        # is fine for developers who want to distribute the generated
557        # source -- but there should be an option to put SWIG output in
558        # the temp dir.
559
560        if self.swig_cpp:
561            log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
562
563        if self.swig_cpp or ('-c++' in self.swig_opts) or \
564           ('-c++' in extension.swig_opts):
565            target_ext = '.cpp'
566        else:
567            target_ext = '.c'
568
569        for source in sources:
570            (base, ext) = os.path.splitext(source)
571            if ext == ".i":             # SWIG interface file
572                new_sources.append(base + '_wrap' + target_ext)
573                swig_sources.append(source)
574                swig_targets[source] = new_sources[-1]
575            else:
576                new_sources.append(source)
577
578        if not swig_sources:
579            return new_sources
580
581        swig = self.swig or self.find_swig()
582        swig_cmd = [swig, "-python"]
583        swig_cmd.extend(self.swig_opts)
584        if self.swig_cpp:
585            swig_cmd.append("-c++")
586
587        # Do not override commandline arguments
588        if not self.swig_opts:
589            for o in extension.swig_opts:
590                swig_cmd.append(o)
591
592        for source in swig_sources:
593            target = swig_targets[source]
594            log.info("swigging %s to %s", source, target)
595            self.spawn(swig_cmd + ["-o", target, source])
596
597        return new_sources
598
599    def find_swig(self):
600        """Return the name of the SWIG executable.  On Unix, this is
601        just "swig" -- it should be in the PATH.  Tries a bit harder on
602        Windows.
603        """
604        if os.name == "posix":
605            return "swig"
606        elif os.name == "nt":
607            # Look for SWIG in its standard installation directory on
608            # Windows (or so I presume!).  If we find it there, great;
609            # if not, act like Unix and assume it's in the PATH.
610            for vers in ("1.3", "1.2", "1.1"):
611                fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
612                if os.path.isfile(fn):
613                    return fn
614            else:
615                return "swig.exe"
616        elif os.name == "os2":
617            # assume swig available in the PATH.
618            return "swig.exe"
619        else:
620            raise DistutilsPlatformError(
621                  "I don't know how to find (much less run) SWIG "
622                  "on platform '%s'" % os.name)
623
624    # -- Name generators -----------------------------------------------
625    # (extension names, filenames, whatever)
626
627    def get_ext_fullname(self, ext_name):
628        if self.package is None:
629            return ext_name
630        else:
631            return self.package + '.' + ext_name
632
633    def get_ext_filename(self, ext_name):
634        r"""Convert the name of an extension (eg. "foo.bar") into the name
635        of the file from which it will be loaded (eg. "foo/bar.so", or
636        "foo\bar.pyd").
637        """
638        from distutils.sysconfig import get_config_var
639        ext_path = ext_name.split('.')
640        # OS/2 has an 8 character module (extension) limit :-(
641        if os.name == "os2":
642            ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
643        # extensions in debug_mode are named 'module_d.pyd' under windows
644        so_ext = get_config_var('SO')
645        if os.name == 'nt' and self.debug:
646            return os.path.join(*ext_path) + '_d' + so_ext
647        return os.path.join(*ext_path) + so_ext
648
649    def get_export_symbols(self, ext):
650        """Return the list of symbols that a shared extension has to
651        export.  This either uses 'ext.export_symbols' or, if it's not
652        provided, "PyInit_" + module_name.  Only relevant on Windows, where
653        the .pyd file (DLL) must export the module "init" function.
654        """
655        initfunc_name = "PyInit_" + ext.name.split('.')[-1]
656        if initfunc_name not in ext.export_symbols:
657            ext.export_symbols.append(initfunc_name)
658        return ext.export_symbols
659
660    def get_libraries(self, ext):
661        """Return the list of libraries to link against when building a
662        shared extension.  On most platforms, this is just 'ext.libraries';
663        on Windows and OS/2, we add the Python library (eg. python20.dll).
664        """
665        # The python library is always needed on Windows.  For MSVC, this
666        # is redundant, since the library is mentioned in a pragma in
667        # pyconfig.h that MSVC groks.  The other Windows compilers all seem
668        # to need it mentioned explicitly, though, so that's what we do.
669        # Append '_d' to the python import library on debug builds.
670        if sys.platform == "win32":
671            from distutils.msvccompiler import MSVCCompiler
672            if not isinstance(self.compiler, MSVCCompiler):
673                template = "python%d%d"
674                if self.debug:
675                    template = template + '_d'
676                pythonlib = (template %
677                       (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
678                # don't extend ext.libraries, it may be shared with other
679                # extensions, it is a reference to the original list
680                return ext.libraries + [pythonlib]
681            else:
682                return ext.libraries
683        elif sys.platform == "os2emx":
684            # EMX/GCC requires the python library explicitly, and I
685            # believe VACPP does as well (though not confirmed) - AIM Apr01
686            template = "python%d%d"
687            # debug versions of the main DLL aren't supported, at least
688            # not at this time - AIM Apr01
689            #if self.debug:
690            #    template = template + '_d'
691            pythonlib = (template %
692                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
693            # don't extend ext.libraries, it may be shared with other
694            # extensions, it is a reference to the original list
695            return ext.libraries + [pythonlib]
696        elif sys.platform[:6] == "cygwin":
697            template = "python%d.%d"
698            pythonlib = (template %
699                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
700            # don't extend ext.libraries, it may be shared with other
701            # extensions, it is a reference to the original list
702            return ext.libraries + [pythonlib]
703        elif sys.platform[:6] == "atheos":
704            from distutils import sysconfig
705
706            template = "python%d.%d"
707            pythonlib = (template %
708                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
709            # Get SHLIBS from Makefile
710            extra = []
711            for lib in sysconfig.get_config_var('SHLIBS').split():
712                if lib.startswith('-l'):
713                    extra.append(lib[2:])
714                else:
715                    extra.append(lib)
716            # don't extend ext.libraries, it may be shared with other
717            # extensions, it is a reference to the original list
718            return ext.libraries + [pythonlib, "m"] + extra
719        elif sys.platform == 'darwin':
720            # Don't use the default code below
721            return ext.libraries
722        else:
723            from distutils import sysconfig
724            if sysconfig.get_config_var('Py_ENABLE_SHARED'):
725                template = "python%d.%d"
726                pythonlib = (template %
727                             (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
728                return ext.libraries + [pythonlib]
729            else:
730                return ext.libraries
731