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