• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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# This module should be kept compatible with Python 2.1.
8
9__revision__ = "$Id$"
10
11import sys, os, string, re
12from types import *
13from site import USER_BASE, USER_SITE
14from distutils.core import Command
15from distutils.errors import *
16from distutils.sysconfig import customize_compiler, get_python_version
17from distutils.dep_util import newer_group
18from distutils.extension import Extension
19from distutils.util import get_platform
20from distutils import log
21
22if os.name == 'nt':
23    from distutils.msvccompiler import get_build_version
24    MSVC_VERSION = int(get_build_version())
25
26# An extension name is just a dot-separated list of Python NAMEs (ie.
27# the same as a fully-qualified module name).
28extension_name_re = re.compile \
29    (r'^[a-zA-Z_][a-zA-Z_0-9]*(\.[a-zA-Z_][a-zA-Z_0-9]*)*$')
30
31
32def show_compilers ():
33    from distutils.ccompiler import show_compilers
34    show_compilers()
35
36
37class build_ext (Command):
38
39    description = "build C/C++ extensions (compile/link to build directory)"
40
41    # XXX thoughts on how to deal with complex command-line options like
42    # these, i.e. how to make it so fancy_getopt can suck them off the
43    # command line and make it look like setup.py defined the appropriate
44    # lists of tuples of what-have-you.
45    #   - each command needs a callback to process its command-line options
46    #   - Command.__init__() needs access to its share of the whole
47    #     command line (must ultimately come from
48    #     Distribution.parse_command_line())
49    #   - it then calls the current command class' option-parsing
50    #     callback to deal with weird options like -D, which have to
51    #     parse the option text and churn out some custom data
52    #     structure
53    #   - that data structure (in this case, a list of 2-tuples)
54    #     will then be present in the command object by the time
55    #     we get to finalize_options() (i.e. the constructor
56    #     takes care of both command-line and client options
57    #     in between initialize_options() and finalize_options())
58
59    sep_by = " (separated by '%s')" % os.pathsep
60    user_options = [
61        ('build-lib=', 'b',
62         "directory for compiled extension modules"),
63        ('build-temp=', 't',
64         "directory for temporary files (build by-products)"),
65        ('plat-name=', 'p',
66         "platform name to cross-compile for, if supported "
67         "(default: %s)" % get_platform()),
68        ('inplace', 'i',
69         "ignore build-lib and put compiled extensions into the source " +
70         "directory alongside your pure Python modules"),
71        ('include-dirs=', 'I',
72         "list of directories to search for header files" + sep_by),
73        ('define=', 'D',
74         "C preprocessor macros to define"),
75        ('undef=', 'U',
76         "C preprocessor macros to undefine"),
77        ('libraries=', 'l',
78         "external C libraries to link with"),
79        ('library-dirs=', 'L',
80         "directories to search for external C libraries" + sep_by),
81        ('rpath=', 'R',
82         "directories to search for shared C libraries at runtime"),
83        ('link-objects=', 'O',
84         "extra explicit link objects to include in the link"),
85        ('debug', 'g',
86         "compile/link with debugging information"),
87        ('force', 'f',
88         "forcibly build everything (ignore file timestamps)"),
89        ('compiler=', 'c',
90         "specify the compiler type"),
91        ('swig-cpp', None,
92         "make SWIG create C++ files (default is C)"),
93        ('swig-opts=', None,
94         "list of SWIG command line options"),
95        ('swig=', None,
96         "path to the SWIG executable"),
97        ('user', None,
98         "add user include, library and rpath"),
99        ]
100
101    boolean_options = ['inplace', 'debug', 'force', 'swig-cpp', 'user']
102
103    help_options = [
104        ('help-compiler', None,
105         "list available compilers", show_compilers),
106        ]
107
108    def initialize_options (self):
109        self.extensions = None
110        self.build_lib = None
111        self.plat_name = None
112        self.build_temp = None
113        self.inplace = 0
114        self.package = None
115
116        self.include_dirs = None
117        self.define = None
118        self.undef = None
119        self.libraries = None
120        self.library_dirs = None
121        self.rpath = None
122        self.link_objects = None
123        self.debug = None
124        self.force = None
125        self.compiler = None
126        self.swig = None
127        self.swig_cpp = None
128        self.swig_opts = None
129        self.user = None
130
131    def finalize_options(self):
132        from distutils import sysconfig
133
134        self.set_undefined_options('build',
135                                   ('build_lib', 'build_lib'),
136                                   ('build_temp', 'build_temp'),
137                                   ('compiler', 'compiler'),
138                                   ('debug', 'debug'),
139                                   ('force', 'force'),
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        # Put the Python "system" include dir at the end, so that
158        # any local include dirs take precedence.
159        self.include_dirs.append(py_include)
160        if plat_py_include != py_include:
161            self.include_dirs.append(plat_py_include)
162
163        self.ensure_string_list('libraries')
164        self.ensure_string_list('link_objects')
165
166        # Life is easier if we're not forever checking for None, so
167        # simplify these options to empty lists if unset
168        if self.libraries is None:
169            self.libraries = []
170        if self.library_dirs is None:
171            self.library_dirs = []
172        elif type(self.library_dirs) is StringType:
173            self.library_dirs = string.split(self.library_dirs, os.pathsep)
174
175        if self.rpath is None:
176            self.rpath = []
177        elif type(self.rpath) is StringType:
178            self.rpath = string.split(self.rpath, os.pathsep)
179
180        # for extensions under windows use different directories
181        # for Release and Debug builds.
182        # also Python's library directory must be appended to library_dirs
183        if os.name == 'nt':
184            # the 'libs' directory is for binary installs - we assume that
185            # must be the *native* platform.  But we don't really support
186            # cross-compiling via a binary install anyway, so we let it go.
187            self.library_dirs.append(os.path.join(sys.exec_prefix, 'libs'))
188            if self.debug:
189                self.build_temp = os.path.join(self.build_temp, "Debug")
190            else:
191                self.build_temp = os.path.join(self.build_temp, "Release")
192
193            # Append the source distribution include and library directories,
194            # this allows distutils on windows to work in the source tree
195            self.include_dirs.append(os.path.join(sys.exec_prefix, 'PC'))
196            if MSVC_VERSION == 9:
197                # Use the .lib files for the correct architecture
198                if self.plat_name == 'win32':
199                    suffix = ''
200                else:
201                    # win-amd64 or win-ia64
202                    suffix = self.plat_name[4:]
203                # We could have been built in one of two places; add both
204                for d in ('PCbuild',), ('PC', 'VS9.0'):
205                    new_lib = os.path.join(sys.exec_prefix, *d)
206                    if suffix:
207                        new_lib = os.path.join(new_lib, suffix)
208                    self.library_dirs.append(new_lib)
209
210            elif MSVC_VERSION == 8:
211                self.library_dirs.append(os.path.join(sys.exec_prefix,
212                                         'PC', 'VS8.0'))
213            elif MSVC_VERSION == 7:
214                self.library_dirs.append(os.path.join(sys.exec_prefix,
215                                         'PC', 'VS7.1'))
216            else:
217                self.library_dirs.append(os.path.join(sys.exec_prefix,
218                                         'PC', 'VC6'))
219
220        # OS/2 (EMX) doesn't support Debug vs Release builds, but has the
221        # import libraries in its "Config" subdirectory
222        if os.name == 'os2':
223            self.library_dirs.append(os.path.join(sys.exec_prefix, 'Config'))
224
225        # for extensions under Cygwin and AtheOS Python's library directory must be
226        # appended to library_dirs
227        if sys.platform[:6] == 'cygwin' or sys.platform[:6] == 'atheos':
228            if sys.executable.startswith(os.path.join(sys.exec_prefix, "bin")):
229                # building third party extensions
230                self.library_dirs.append(os.path.join(sys.prefix, "lib",
231                                                      "python" + get_python_version(),
232                                                      "config"))
233            else:
234                # building python standard extensions
235                self.library_dirs.append('.')
236
237        # For building extensions with a shared Python library,
238        # Python's library directory must be appended to library_dirs
239        # See Issues: #1600860, #4366
240        if (sysconfig.get_config_var('Py_ENABLE_SHARED')):
241            if not sysconfig.python_build:
242                # building third party extensions
243                self.library_dirs.append(sysconfig.get_config_var('LIBDIR'))
244            else:
245                # building python standard extensions
246                self.library_dirs.append('.')
247
248        # The argument parsing will result in self.define being a string, but
249        # it has to be a list of 2-tuples.  All the preprocessor symbols
250        # specified by the 'define' option will be set to '1'.  Multiple
251        # symbols can be separated with commas.
252
253        if self.define:
254            defines = self.define.split(',')
255            self.define = map(lambda symbol: (symbol, '1'), defines)
256
257        # The option for macros to undefine is also a string from the
258        # option parsing, but has to be a list.  Multiple symbols can also
259        # be separated with commas here.
260        if self.undef:
261            self.undef = self.undef.split(',')
262
263        if self.swig_opts is None:
264            self.swig_opts = []
265        else:
266            self.swig_opts = self.swig_opts.split(' ')
267
268        # Finally add the user include and library directories if requested
269        if self.user:
270            user_include = os.path.join(USER_BASE, "include")
271            user_lib = os.path.join(USER_BASE, "lib")
272            if os.path.isdir(user_include):
273                self.include_dirs.append(user_include)
274            if os.path.isdir(user_lib):
275                self.library_dirs.append(user_lib)
276                self.rpath.append(user_lib)
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
428        return filenames
429
430    def get_outputs(self):
431        # Sanity check the 'extensions' list -- can't assume this is being
432        # done in the same run as a 'build_extensions()' call (in fact, we
433        # can probably assume that it *isn't*!).
434        self.check_extensions_list(self.extensions)
435
436        # And build the list of output (built) filenames.  Note that this
437        # ignores the 'inplace' flag, and assumes everything goes in the
438        # "build" tree.
439        outputs = []
440        for ext in self.extensions:
441            outputs.append(self.get_ext_fullpath(ext.name))
442        return outputs
443
444    def build_extensions(self):
445        # First, sanity-check the 'extensions' list
446        self.check_extensions_list(self.extensions)
447
448        for ext in self.extensions:
449            self.build_extension(ext)
450
451    def build_extension(self, ext):
452        sources = ext.sources
453        if sources is None or type(sources) not in (ListType, TupleType):
454            raise DistutilsSetupError, \
455                  ("in 'ext_modules' option (extension '%s'), " +
456                   "'sources' must be present and must be " +
457                   "a list of source filenames") % ext.name
458        sources = list(sources)
459
460        ext_path = self.get_ext_fullpath(ext.name)
461        depends = sources + ext.depends
462        if not (self.force or newer_group(depends, ext_path, 'newer')):
463            log.debug("skipping '%s' extension (up-to-date)", ext.name)
464            return
465        else:
466            log.info("building '%s' extension", ext.name)
467
468        # First, scan the sources for SWIG definition files (.i), run
469        # SWIG on 'em to create .c files, and modify the sources list
470        # accordingly.
471        sources = self.swig_sources(sources, ext)
472
473        # Next, compile the source code to object files.
474
475        # XXX not honouring 'define_macros' or 'undef_macros' -- the
476        # CCompiler API needs to change to accommodate this, and I
477        # want to do one thing at a time!
478
479        # Two possible sources for extra compiler arguments:
480        #   - 'extra_compile_args' in Extension object
481        #   - CFLAGS environment variable (not particularly
482        #     elegant, but people seem to expect it and I
483        #     guess it's useful)
484        # The environment variable should take precedence, and
485        # any sensible compiler will give precedence to later
486        # command line args.  Hence we combine them in order:
487        extra_args = ext.extra_compile_args or []
488
489        macros = ext.define_macros[:]
490        for undef in ext.undef_macros:
491            macros.append((undef,))
492
493        objects = self.compiler.compile(sources,
494                                         output_dir=self.build_temp,
495                                         macros=macros,
496                                         include_dirs=ext.include_dirs,
497                                         debug=self.debug,
498                                         extra_postargs=extra_args,
499                                         depends=ext.depends)
500
501        # XXX -- this is a Vile HACK!
502        #
503        # The setup.py script for Python on Unix needs to be able to
504        # get this list so it can perform all the clean up needed to
505        # avoid keeping object files around when cleaning out a failed
506        # build of an extension module.  Since Distutils does not
507        # track dependencies, we have to get rid of intermediates to
508        # ensure all the intermediates will be properly re-built.
509        #
510        self._built_objects = objects[:]
511
512        # Now link the object files together into a "shared object" --
513        # of course, first we have to figure out all the other things
514        # that go into the mix.
515        if ext.extra_objects:
516            objects.extend(ext.extra_objects)
517        extra_args = ext.extra_link_args or []
518
519        # Detect target language, if not provided
520        language = ext.language or self.compiler.detect_language(sources)
521
522        self.compiler.link_shared_object(
523            objects, ext_path,
524            libraries=self.get_libraries(ext),
525            library_dirs=ext.library_dirs,
526            runtime_library_dirs=ext.runtime_library_dirs,
527            extra_postargs=extra_args,
528            export_symbols=self.get_export_symbols(ext),
529            debug=self.debug,
530            build_temp=self.build_temp,
531            target_lang=language)
532
533
534    def swig_sources (self, sources, extension):
535
536        """Walk the list of source files in 'sources', looking for SWIG
537        interface (.i) files.  Run SWIG on all that are found, and
538        return a modified 'sources' list with SWIG source files replaced
539        by the generated C (or C++) files.
540        """
541
542        new_sources = []
543        swig_sources = []
544        swig_targets = {}
545
546        # XXX this drops generated C/C++ files into the source tree, which
547        # is fine for developers who want to distribute the generated
548        # source -- but there should be an option to put SWIG output in
549        # the temp dir.
550
551        if self.swig_cpp:
552            log.warn("--swig-cpp is deprecated - use --swig-opts=-c++")
553
554        if self.swig_cpp or ('-c++' in self.swig_opts) or \
555           ('-c++' in extension.swig_opts):
556            target_ext = '.cpp'
557        else:
558            target_ext = '.c'
559
560        for source in sources:
561            (base, ext) = os.path.splitext(source)
562            if ext == ".i":             # SWIG interface file
563                new_sources.append(base + '_wrap' + target_ext)
564                swig_sources.append(source)
565                swig_targets[source] = new_sources[-1]
566            else:
567                new_sources.append(source)
568
569        if not swig_sources:
570            return new_sources
571
572        swig = self.swig or self.find_swig()
573        swig_cmd = [swig, "-python"]
574        swig_cmd.extend(self.swig_opts)
575        if self.swig_cpp:
576            swig_cmd.append("-c++")
577
578        # Do not override commandline arguments
579        if not self.swig_opts:
580            for o in extension.swig_opts:
581                swig_cmd.append(o)
582
583        for source in swig_sources:
584            target = swig_targets[source]
585            log.info("swigging %s to %s", source, target)
586            self.spawn(swig_cmd + ["-o", target, source])
587
588        return new_sources
589
590    # swig_sources ()
591
592    def find_swig (self):
593        """Return the name of the SWIG executable.  On Unix, this is
594        just "swig" -- it should be in the PATH.  Tries a bit harder on
595        Windows.
596        """
597
598        if os.name == "posix":
599            return "swig"
600        elif os.name == "nt":
601
602            # Look for SWIG in its standard installation directory on
603            # Windows (or so I presume!).  If we find it there, great;
604            # if not, act like Unix and assume it's in the PATH.
605            for vers in ("1.3", "1.2", "1.1"):
606                fn = os.path.join("c:\\swig%s" % vers, "swig.exe")
607                if os.path.isfile(fn):
608                    return fn
609            else:
610                return "swig.exe"
611
612        elif os.name == "os2":
613            # assume swig available in the PATH.
614            return "swig.exe"
615
616        else:
617            raise DistutilsPlatformError, \
618                  ("I don't know how to find (much less run) SWIG "
619                   "on platform '%s'") % os.name
620
621    # find_swig ()
622
623    # -- Name generators -----------------------------------------------
624    # (extension names, filenames, whatever)
625    def get_ext_fullpath(self, ext_name):
626        """Returns the path of the filename for a given extension.
627
628        The file is located in `build_lib` or directly in the package
629        (inplace option).
630        """
631        # makes sure the extension name is only using dots
632        all_dots = string.maketrans('/'+os.sep, '..')
633        ext_name = ext_name.translate(all_dots)
634
635        fullname = self.get_ext_fullname(ext_name)
636        modpath = fullname.split('.')
637        filename = self.get_ext_filename(ext_name)
638        filename = os.path.split(filename)[-1]
639
640        if not self.inplace:
641            # no further work needed
642            # returning :
643            #   build_dir/package/path/filename
644            filename = os.path.join(*modpath[:-1]+[filename])
645            return os.path.join(self.build_lib, filename)
646
647        # the inplace option requires to find the package directory
648        # using the build_py command for that
649        package = '.'.join(modpath[0:-1])
650        build_py = self.get_finalized_command('build_py')
651        package_dir = os.path.abspath(build_py.get_package_dir(package))
652
653        # returning
654        #   package_dir/filename
655        return os.path.join(package_dir, filename)
656
657    def get_ext_fullname(self, ext_name):
658        """Returns the fullname of a given extension name.
659
660        Adds the `package.` prefix"""
661        if self.package is None:
662            return ext_name
663        else:
664            return self.package + '.' + ext_name
665
666    def get_ext_filename(self, ext_name):
667        r"""Convert the name of an extension (eg. "foo.bar") into the name
668        of the file from which it will be loaded (eg. "foo/bar.so", or
669        "foo\bar.pyd").
670        """
671        from distutils.sysconfig import get_config_var
672        ext_path = string.split(ext_name, '.')
673        # OS/2 has an 8 character module (extension) limit :-(
674        if os.name == "os2":
675            ext_path[len(ext_path) - 1] = ext_path[len(ext_path) - 1][:8]
676        # extensions in debug_mode are named 'module_d.pyd' under windows
677        so_ext = get_config_var('SO')
678        if os.name == 'nt' and self.debug:
679            return os.path.join(*ext_path) + '_d' + so_ext
680        return os.path.join(*ext_path) + so_ext
681
682    def get_export_symbols (self, ext):
683        """Return the list of symbols that a shared extension has to
684        export.  This either uses 'ext.export_symbols' or, if it's not
685        provided, "init" + module_name.  Only relevant on Windows, where
686        the .pyd file (DLL) must export the module "init" function.
687        """
688        initfunc_name = "init" + ext.name.split('.')[-1]
689        if initfunc_name not in ext.export_symbols:
690            ext.export_symbols.append(initfunc_name)
691        return ext.export_symbols
692
693    def get_libraries (self, ext):
694        """Return the list of libraries to link against when building a
695        shared extension.  On most platforms, this is just 'ext.libraries';
696        on Windows and OS/2, we add the Python library (eg. python20.dll).
697        """
698        # The python library is always needed on Windows.  For MSVC, this
699        # is redundant, since the library is mentioned in a pragma in
700        # pyconfig.h that MSVC groks.  The other Windows compilers all seem
701        # to need it mentioned explicitly, though, so that's what we do.
702        # Append '_d' to the python import library on debug builds.
703        if sys.platform == "win32":
704            from distutils.msvccompiler import MSVCCompiler
705            if not isinstance(self.compiler, MSVCCompiler):
706                template = "python%d%d"
707                if self.debug:
708                    template = template + '_d'
709                pythonlib = (template %
710                       (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
711                # don't extend ext.libraries, it may be shared with other
712                # extensions, it is a reference to the original list
713                return ext.libraries + [pythonlib]
714            else:
715                return ext.libraries
716        elif sys.platform == "os2emx":
717            # EMX/GCC requires the python library explicitly, and I
718            # believe VACPP does as well (though not confirmed) - AIM Apr01
719            template = "python%d%d"
720            # debug versions of the main DLL aren't supported, at least
721            # not at this time - AIM Apr01
722            #if self.debug:
723            #    template = template + '_d'
724            pythonlib = (template %
725                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
726            # don't extend ext.libraries, it may be shared with other
727            # extensions, it is a reference to the original list
728            return ext.libraries + [pythonlib]
729        elif sys.platform[:6] == "cygwin":
730            template = "python%d.%d"
731            pythonlib = (template %
732                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
733            # don't extend ext.libraries, it may be shared with other
734            # extensions, it is a reference to the original list
735            return ext.libraries + [pythonlib]
736        elif sys.platform[:6] == "atheos":
737            from distutils import sysconfig
738
739            template = "python%d.%d"
740            pythonlib = (template %
741                   (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
742            # Get SHLIBS from Makefile
743            extra = []
744            for lib in sysconfig.get_config_var('SHLIBS').split():
745                if lib.startswith('-l'):
746                    extra.append(lib[2:])
747                else:
748                    extra.append(lib)
749            # don't extend ext.libraries, it may be shared with other
750            # extensions, it is a reference to the original list
751            return ext.libraries + [pythonlib, "m"] + extra
752
753        elif sys.platform == 'darwin':
754            # Don't use the default code below
755            return ext.libraries
756        elif sys.platform[:3] == 'aix':
757            # Don't use the default code below
758            return ext.libraries
759        else:
760            from distutils import sysconfig
761            if sysconfig.get_config_var('Py_ENABLE_SHARED'):
762                template = "python%d.%d"
763                pythonlib = (template %
764                             (sys.hexversion >> 24, (sys.hexversion >> 16) & 0xff))
765                return ext.libraries + [pythonlib]
766            else:
767                return ext.libraries
768
769# class build_ext
770