PageRenderTime 53ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/distutils/command/build_ext.py

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