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