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