PageRenderTime 51ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/CPython/27/Lib/distutils/command/build_ext.py

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