build_ext.py revision 3679727939a9d25ccfe057e71e8a4b8be73d47ce
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 distutils.core import Command
11from distutils.errors import *
12from distutils.sysconfig import customize_compiler, get_python_version
13from distutils.dep_util import newer_group
14from distutils.extension import Extension
15from distutils.util import get_platform
16from distutils import log
17
18# this keeps compatibility from 2.3 to 2.5
19if sys.version < "2.6":
20    USER_BASE = None
21    HAS_USER_SITE = False
22else:
23    from site import USER_BASE
24    HAS_USER_SITE = True
25
26if os.name == 'nt':
27    from distutils.msvccompiler import get_build_version
28    MSVC_VERSION = int(get_build_version())
29
30# An extension name is just a dot-separated list of Python NAMEs (ie.
31# the same as a fully-qualified module name).
32extension_name_re = re.compile \
33    (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
34
35
36def show_compilers ():
37    from distutils.ccompiler import show_compilers
38    show_compilers()
39
40
41class build_ext(Command):
42
43    description = "build C/C++ extensions (compile/link to build directory)"
44
45    # XXX thoughts on how to deal with complex command-line options like
46    # these, i.e. how to make it so fancy_getopt can suck them off the
47    # command line and make it look like setup.py defined the appropriate
48    # lists of tuples of what-have-you.
49    #   - each command needs a callback to process its command-line options
50    #   - Command.__init__() needs access to its share of the whole
51    #     command line (must ultimately come from
52    #     Distribution.parse_command_line())
53    #   - it then calls the current command class' option-parsing
54    #     callback to deal with weird options like -D, which have to
55    #     parse the option text and churn out some custom data
56    #     structure
57    #   - that data structure (in this case, a list of 2-tuples)
58    #     will then be present in the command object by the time
59    #     we get to finalize_options() (i.e. the constructor
60    #     takes care of both command-line and client options
61    #     in between initialize_options() and finalize_options())
62
63    sep_by = " (separated by '%s')" % os.pathsep
64    user_options = [
65        ('build-lib=', 'b',
66         "directory for compiled extension modules"),
67        ('build-temp=', 't',
68         "directory for temporary files (build by-products)"),
69        ('plat-name=', 'p',
70         "platform name to cross-compile for, if supported "
71         "(default: %s)" % get_platform()),
72        ('inplace', 'i',
73         "ignore build-lib and put compiled extensions into the source " +
74         "directory alongside your pure Python modules"),
75        ('include-dirs=', 'I',
76         "list of directories to search for header files" + sep_by),
77        ('define=', 'D',
78         "C preprocessor macros to define"),
79        ('undef=', 'U',
80         "C preprocessor macros to undefine"),
81        ('libraries=', 'l',
82         "external C libraries to link with"),
83        ('library-dirs=', 'L',
84         "directories to search for external C libraries" + sep_by),
85        ('rpath=', 'R',
86         "directories to search for shared C libraries at runtime"),
87        ('link-objects=', 'O',
88         "extra explicit link objects to include in the link"),
89        ('debug', 'g',
90         "compile/link with debugging information"),
91        ('force', 'f',
92         "forcibly build everything (ignore file timestamps)"),
93        ('compiler=', 'c',
94         "specify the compiler type"),
95        ('swig-cpp', None,
96         "make SWIG create C++ files (default is C)"),
97        ('swig-opts=', None,
98         "list of SWIG command line options"),
99        ('swig=', None,
100         "path to the SWIG executable"),
101        ]
102
103    boolean_options = ['inplace', 'debug', 'force', 'swig-cpp']
104
105    if HAS_USER_SITE:
106        user_options.append(('user', None,
107                             "add user include, library and rpath"))
108        boolean_options.append('user')
109
110    help_options = [
111        ('help-compiler', None,
112         "list available compilers", show_compilers),
113        ]
114
115    def initialize_options(self):
116        self.extensions = None
117        self.build_lib = None
118        self.plat_name = None
119        self.build_temp = None
120        self.inplace = 0
121        self.package = None
122
123        self.include_dirs = None
124        self.define = None
125        self.undef = None
126        self.libraries = None
127        self.library_dirs = None
128        self.rpath = None
129        self.link_objects = None
130        self.debug = None
131        self.force = None
132        self.compiler = None
133        self.swig = None
134        self.swig_cpp = None
135        self.swig_opts = None
136        self.user = None
137
138    def finalize_options(self):
139        from distutils import sysconfig
140
141        self.set_undefined_options('build',
142                                   ('build_lib', 'build_lib'),
143                                   ('build_temp', 'build_temp'),
144                                   ('compiler', 'compiler'),
145                                   ('debug', 'debug'),
146                                   ('force', 'force'),
147                                   ('plat_name', 'plat_name'),
148                                   )
149
150        if self.package is None:
151            self.package = self.distribution.ext_package
152
153        self.extensions = self.distribution.ext_modules
154
155        # Make sure Python's include directories (for Python.h, pyconfig.h,
156        # etc.) are in the include search path.
157        py_include = sysconfig.get_python_inc()
158        plat_py_include = sysconfig.get_python_inc(plat_specific=1)
159        if self.include_dirs is None:
160            self.include_dirs = self.distribution.include_dirs or []
161        if isinstance(self.include_dirs, str):
162            self.include_dirs = self.include_dirs.split(os.pathsep)
163
164        # Put the Python "system" include dir at the end, so that
165        # any local include dirs take precedence.
166        self.include_dirs.append(py_include)
167        if plat_py_include != py_include:
168            self.include_dirs.append(plat_py_include)
169
170        if isinstance(self.libraries, str):
171            self.libraries = [self.libraries]
172
173        # Life is easier if we're not forever checking for None, so
174        # simplify these options to empty lists if unset
175        if self.libraries is None:
176            self.libraries = []
177        if self.library_dirs is None:
178            self.library_dirs = []
179        elif isinstance(self.library_dirs, str):
180            self.library_dirs = self.library_dirs.split(os.pathsep)
181
182        if self.rpath is None:
183            self.rpath = []
184        elif isinstance(self.rpath, str):
185            self.rpath = self.rpath.split(os.pathsep)
186
187        # for extensions under windows use different directories
188        # for Release and Debug builds.
189        # also Python's library directory must be appended to library_dirs
190        if os.name == 'nt':
191            # the 'libs' directory is for binary installs - we assume that
192            # must be the *native* platform.  But we don't really support
193            # cross-compiling via a binary install anyway, so we let it go.
194            self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
195            if self.debug:
196                self.build_temp = os.path.join(self.build_temp, "Debug")
197            else:
198                self.build_temp = os.path.join(self.build_temp, "Release")
199
200            # Append the source distribution include and library directories,
201            # this allows distutils on windows to work in the source tree
202            self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC'))
203            if MSVC_VERSION == 9:
204                # Use the .lib files for the correct architecture
205                if self.plat_name == 'win32':
206                    suffix = ''
207                else:
208                    # win-amd64 or win-ia64
209                    suffix = self.plat_name[4:]
210                new_lib = os.path.join(sys.exec_prefix, 'PCbuild')
211                if suffix:
212                    new_lib = os.path.join(new_lib, suffix)
213                self.library_dirs.append(new_lib)
214
215            elif MSVC_VERSION == 8:
216                self.library_dirs.append(os.path.join(sys.exec_prefix,
217                                         'PC', 'VS8.0', 'win32release'))
218            elif MSVC_VERSION == 7:
219                self.library_dirs.append(os.path.join(sys.exec_prefix,
220                                         'PC', 'VS7.1'))
221            else:
222                self.library_dirs.append(os.path.join(sys.exec_prefix,
223                                         'PC', 'VC6'))
224
225        # OS/2 (EMX) doesn't support Debug vs Release builds, but has the
226        # import libraries in its "Config" subdirectory
227        if os.name == 'os2':
228            self.library_dirs.append(os.path.join(sys.exec_prefix, 'Config'))
229
230        # for extensions under Cygwin and AtheOS Python's library directory must be
231        # appended to library_dirs
232        if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
233            if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
234                # building third party extensions
235                self.library_dirs.append(os.path.join(sys.prefix, "lib",
236                                                      "python" + get_python_version(),
237                                                      "config"))
238            else:
239                # building python standard extensions
240                self.library_dirs.append('.')
241
242        # for extensions under Linux or Solaris with a shared Python library,
243        # Python's library directory must be appended to library_dirs
244        sysconfig.get_config_var('Py_ENABLE_SHARED')
245        if ((sys.platform.startswith('linux') or sys.platform.startswith('gnu')
246             or sys.platform.startswith('sunos'))
247            and sysconfig.get_config_var('Py_ENABLE_SHARED')):
248            if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
249                # building third party extensions
250                self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
251            else:
252                # building python standard extensions
253                self.library_dirs.append('.')
254
255        # The argument parsing will result in self.define being a string, but
256        # it has to be a list of 2-tuples.  All the preprocessor symbols
257        # specified by the 'define' option will be set to '1'.  Multiple
258        # symbols can be separated with commas.
259
260        if self.define:
261            defines = self.define.split(',')
262            self.define = [(symbol, '1') for symbol in defines]
263
264        # The option for macros to undefine is also a string from the
265        # option parsing, but has to be a list.  Multiple symbols can also
266        # be separated with commas here.
267        if self.undef:
268            self.undef = self.undef.split(',')
269
270        if self.swig_opts is None:
271            self.swig_opts = []
272        else:
273            self.swig_opts = self.swig_opts.split(' ')
274
275        # Finally add the user include and library directories if requested
276        if self.user:
277            user_include = os.path.join(USER_BASE, "include")
278            user_lib = os.path.join(USER_BASE, "lib")
279            if os.path.isdir(user_include):
280                self.include_dirs.append(user_include)
281            if os.path.isdir(user_lib):
282                self.library_dirs.append(user_lib)
283                self.rpath.append(user_lib)
284
285    def run(self):
286        from distutils.ccompiler import new_compiler
287
288        # 'self.extensions', as supplied by setup.py, is a list of
289        # Extension instances.  See the documentation for Extension (in
290        # distutils.extension) for details.
291        #
292        # For backwards compatibility with Distutils 0.8.2 and earlier, we
293        # also allow the 'extensions' list to be a list of tuples:
294        #    (ext_name, build_info)
295        # where build_info is a dictionary containing everything that
296        # Extension instances do except the name, with a few things being
297        # differently named.  We convert these 2-tuples to Extension
298        # instances as needed.
299
300        if not self.extensions:
301            return
302
303        # If we were asked to build any C/C++ libraries, make sure that the
304        # directory where we put them is in the library search path for
305        # linking extensions.
306        if self.distribution.has_c_libraries():
307            build_clib = self.get_finalized_command('build_clib')
308            self.libraries.extend(build_clib.get_library_names() or [])
309            self.library_dirs.append(build_clib.build_clib)
310
311        # Setup the CCompiler object that we'll use to do all the
312        # compiling and linking
313        self.compiler = new_compiler(compiler=self.compiler,
314                                     verbose=self.verbose,
315                                     dry_run=self.dry_run,
316                                     force=self.force)
317        customize_compiler(self.compiler)
318        # If we are cross-compiling, init the compiler now (if we are not
319        # cross-compiling, init would not hurt, but people may rely on
320        # late initialization of compiler even if they shouldn't...)
321        if os.name == 'nt' and self.plat_name != get_platform():
322            self.compiler.initialize(self.plat_name)
323
324        # And make sure that any compile/link-related options (which might
325        # come from the command-line or from the setup script) are set in
326        # that CCompiler object -- that way, they automatically apply to
327        # all compiling and linking done here.
328        if self.include_dirs is not None:
329            self.compiler.set_include_dirs(self.include_dirs)
330        if self.define is not None:
331            # 'define' option is a list of (name,value) tuples
332            for (name, value) in self.define:
333                self.compiler.define_macro(name, value)
334        if self.undef is not None:
335            for macro in self.undef:
336                self.compiler.undefine_macro(macro)
337        if self.libraries is not None:
338            self.compiler.set_libraries(self.libraries)
339        if self.library_dirs is not None:
340            self.compiler.set_library_dirs(self.library_dirs)
341        if self.rpath is not None:
342            self.compiler.set_runtime_library_dirs(self.rpath)
343        if self.link_objects is not None:
344            self.compiler.set_link_objects(self.link_objects)
345
346        # Now actually compile and link everything.
347        self.build_extensions()
348
349    def check_extensions_list(self, extensions):
350        """Ensure that the list of extensions (presumably provided as a
351        command option 'extensions') is valid, i.e. it is a list of
352        Extension objects.  We also support the old-style list of 2-tuples,
353        where the tuples are (ext_name, build_info), which are converted to
354        Extension instances here.
355
356        Raise DistutilsSetupError if the structure is invalid anywhere;
357        just returns otherwise.
358        """
359        if not isinstance(extensions, list):
360            raise DistutilsSetupError(
361                  "'ext_modules' option must be a list of Extension instances")
362
363        for i, ext in enumerate(extensions):
364            if isinstance(ext, Extension):
365                continue                # OK! (assume type-checking done
366                                        # by Extension constructor)
367
368            if not isinstance(ext, tuple) or len(ext) != 2:
369                raise DistutilsSetupError(
370                       "each element of 'ext_modules' option must be an "
371                       "Extension instance or 2-tuple")
372
373            ext_name, build_info = ext
374
375            log.warn(("old-style (ext_name, build_info) tuple found in "
376                      "ext_modules for extension '%s'"
377                      "-- please convert to Extension instance" % ext_name))
378
379            if not (isinstance(ext_name, str) and
380                    extension_name_re.match(ext_name)):
381                raise DistutilsSetupError(
382                       "first element of each tuple in 'ext_modules' "
383                       "must be the extension name (a string)")
384
385            if not isinstance(build_info, dict):
386                raise DistutilsSetupError(
387                       "second element of each tuple in 'ext_modules' "
388                       "must be a dictionary (build info)")
389
390            # OK, the (ext_name, build_info) dict is type-safe: convert it
391            # to an Extension instance.
392            ext = Extension(ext_name, build_info['sources'])
393
394            # Easy stuff: one-to-one mapping from dict elements to
395            # instance attributes.
396            for key in ('include_dirs', 'library_dirs', 'libraries',
397                        'extra_objects', 'extra_compile_args',
398                        'extra_link_args'):
399                val = build_info.get(key)
400                if val is not None:
401                    setattr(ext, key, val)
402
403            # Medium-easy stuff: same syntax/semantics, different names.
404            ext.runtime_library_dirs = build_info.get('rpath')
405            if 'def_file' in build_info:
406                log.warn("'def_file' element of build info dict "
407                         "no longer supported")
408
409            # Non-trivial stuff: 'macros' split into 'define_macros'
410            # and 'undef_macros'.
411            macros = build_info.get('macros')
412            if macros:
413                ext.define_macros = []
414                ext.undef_macros = []
415                for macro in macros:
416                    if not (isinstance(macro, tuple) and len(macro) in (1, 2)):
417                        raise DistutilsSetupError(
418                              "'macros' element of build info dict "
419                              "must be 1- or 2-tuple")
420                    if len(macro) == 1:
421                        ext.undef_macros.append(macro[0])
422                    elif len(macro) == 2:
423                        ext.define_macros.append(macro)
424
425            extensions[i] = ext
426
427    def get_source_files(self):
428        self.check_extensions_list(self.extensions)
429        filenames = []
430
431        # Wouldn't it be neat if we knew the names of header files too...
432        for ext in self.extensions:
433            filenames.extend(ext.sources)
434        return filenames
435
436    def get_outputs(self):
437        # Sanity check the 'extensions' list -- can't assume this is being
438        # done in the same run as a 'build_extensions()' call (in fact, we
439        # can probably assume that it *isn't*!).
440        self.check_extensions_list(self.extensions)
441
442        # And build the list of output (built) filenames.  Note that this
443        # ignores the 'inplace' flag, and assumes everything goes in the
444        # "build" tree.
445        outputs = []
446        for ext in self.extensions:
447            outputs.append(self.get_ext_fullpath(ext.name))
448        return outputs
449
450    def build_extensions(self):
451        # First, sanity-check the 'extensions' list
452        self.check_extensions_list(self.extensions)
453
454        for ext in self.extensions:
455            try:
456                self.build_extension(ext)
457            except (CCompilerError, DistutilsError, CompileError) as e:
458                if not ext.optional:
459                    raise
460                self.warn('building extension "%s" failed: %s' %
461                          (ext.name, e))
462
463    def build_extension(self, ext):
464        sources = ext.sources
465        if sources is None or not isinstance(sources, (list, tuple)):
466            raise DistutilsSetupError(
467                  "in 'ext_modules' option (extension '%s'), "
468                  "'sources' must be present and must be "
469                  "a list of source filenames" % ext.name)
470        sources = list(sources)
471
472        ext_path = self.get_ext_fullpath(ext.name)
473        depends = sources + ext.depends
474        if not (self.force or newer_group(depends, ext_path, '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_path,
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    def get_ext_fullpath(self, ext_name):
627        """Returns the path of the filename for a given extension.
628
629        The file is located in `build_lib` or directly in the package
630        (inplace option).
631        """
632        fullname = self.get_ext_fullname(ext_name)
633        modpath = fullname.split('.')
634        filename = self.get_ext_filename(modpath[-1])
635
636        if not self.inplace:
637            # no further work needed
638            # returning :
639            #   build_dir/package/path/filename
640            filename = os.path.join(*modpath[:-1]+[filename])
641            return os.path.join(self.build_lib, filename)
642
643        # the inplace option requires to find the package directory
644        # using the build_py command for that
645        package = '.'.join(modpath[0:-1])
646        build_py = self.get_finalized_command('build_py')
647        package_dir = os.path.abspath(build_py.get_package_dir(package))
648
649        # returning
650        #   package_dir/filename
651        return os.path.join(package_dir, filename)
652
653    def get_ext_fullname(self, ext_name):
654        """Returns the fullname of a given extension name.
655
656        Adds the `package.` prefix"""
657        if self.package is None:
658            return ext_name
659        else:
660            return self.package + '.' + ext_name
661
662    def get_ext_filename(self, ext_name):
663        r"""Convert the name of an extension (eg. "foo.bar") into the name
664        of the file from which it will be loaded (eg. "foo/bar.so", or
665        "foo\bar.pyd").
666        """
667        from distutils.sysconfig import get_config_var
668        ext_path = ext_name.split('.')
669        # OS/2 has an 8 character module (extension) limit :-(
670        if os.name == "os2":
671            ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
672        # extensions in debug_mode are named 'module_d.pyd' under windows
673        so_ext = get_config_var('SO')
674        if os.name == 'nt' and self.debug:
675            return os.path.join(*ext_path) + '_d' + so_ext
676        return os.path.join(*ext_path) + so_ext
677
678    def get_export_symbols(self, ext):
679        """Return the list of symbols that a shared extension has to
680        export.  This either uses 'ext.export_symbols' or, if it's not
681        provided, "PyInit_" + module_name.  Only relevant on Windows, where
682        the .pyd file (DLL) must export the module "PyInit_" function.
683        """
684        initfunc_name = "PyInit_" + ext.name.split('.')[-1]
685        if initfunc_name not in ext.export_symbols:
686            ext.export_symbols.append(initfunc_name)
687        return ext.export_symbols
688
689    def get_libraries(self, ext):
690        """Return the list of libraries to link against when building a
691        shared extension.  On most platforms, this is just 'ext.libraries';
692        on Windows and OS/2, we add the Python library (eg. python20.dll).
693        """
694        # The python library is always needed on Windows.  For MSVC, this
695        # is redundant, since the library is mentioned in a pragma in
696        # pyconfig.h that MSVC groks.  The other Windows compilers all seem
697        # to need it mentioned explicitly, though, so that's what we do.
698        # Append '_d' to the python import library on debug builds.
699        if sys.platform == "win32":
700            from distutils.msvccompiler import MSVCCompiler
701            if not isinstance(self.compiler, MSVCCompiler):
702                template = "python%d%d"
703                if self.debug:
704                    template = template + '_d'
705                pythonlib = (template %
706                       (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
707                # don't extend ext.libraries, it may be shared with other
708                # extensions, it is a reference to the original list
709                return ext.libraries + [pythonlib]
710            else:
711                return ext.libraries
712        elif sys.platform == "os2emx":
713            # EMX/GCC requires the python library explicitly, and I
714            # believe VACPP does as well (though not confirmed) - AIM Apr01
715            template = "python%d%d"
716            # debug versions of the main DLL aren't supported, at least
717            # not at this time - AIM Apr01
718            #if self.debug:
719            #    template = template + '_d'
720            pythonlib = (template %
721                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
722            # don't extend ext.libraries, it may be shared with other
723            # extensions, it is a reference to the original list
724            return ext.libraries + [pythonlib]
725        elif sys.platform[:6] == "cygwin":
726            template = "python%d.%d"
727            pythonlib = (template %
728                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
729            # don't extend ext.libraries, it may be shared with other
730            # extensions, it is a reference to the original list
731            return ext.libraries + [pythonlib]
732        elif sys.platform[:6] == "atheos":
733            from distutils import sysconfig
734
735            template = "python%d.%d"
736            pythonlib = (template %
737                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
738            # Get SHLIBS from Makefile
739            extra = []
740            for lib in sysconfig.get_config_var('SHLIBS').split():
741                if lib.startswith('-l'):
742                    extra.append(lib[2:])
743                else:
744                    extra.append(lib)
745            # don't extend ext.libraries, it may be shared with other
746            # extensions, it is a reference to the original list
747            return ext.libraries + [pythonlib, "m"] + extra
748        elif sys.platform == 'darwin':
749            # Don't use the default code below
750            return ext.libraries
751        else:
752            from distutils import sysconfig
753            if sysconfig.get_config_var('Py_ENABLE_SHARED'):
754                template = "python%d.%d"
755                pythonlib = (template %
756                             (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
757                return ext.libraries + [pythonlib]
758            else:
759                return ext.libraries
760