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