ccompiler.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. import os
  2. import re
  3. import sys
  4. import platform
  5. import shlex
  6. import time
  7. import subprocess
  8. from copy import copy
  9. from pathlib import Path
  10. from distutils import ccompiler
  11. from distutils.ccompiler import (
  12. compiler_class, gen_lib_options, get_default_compiler, new_compiler,
  13. CCompiler
  14. )
  15. from distutils.errors import (
  16. DistutilsExecError, DistutilsModuleError, DistutilsPlatformError,
  17. CompileError, UnknownFileError
  18. )
  19. from distutils.sysconfig import customize_compiler
  20. from distutils.version import LooseVersion
  21. from numpy.distutils import log
  22. from numpy.distutils.exec_command import (
  23. filepath_from_subprocess_output, forward_bytes_to_stdout
  24. )
  25. from numpy.distutils.misc_util import cyg2win32, is_sequence, mingw32, \
  26. get_num_build_jobs, \
  27. _commandline_dep_string, \
  28. sanitize_cxx_flags
  29. # globals for parallel build management
  30. import threading
  31. _job_semaphore = None
  32. _global_lock = threading.Lock()
  33. _processing_files = set()
  34. def _needs_build(obj, cc_args, extra_postargs, pp_opts):
  35. """
  36. Check if an objects needs to be rebuild based on its dependencies
  37. Parameters
  38. ----------
  39. obj : str
  40. object file
  41. Returns
  42. -------
  43. bool
  44. """
  45. # defined in unixcompiler.py
  46. dep_file = obj + '.d'
  47. if not os.path.exists(dep_file):
  48. return True
  49. # dep_file is a makefile containing 'object: dependencies'
  50. # formatted like posix shell (spaces escaped, \ line continuations)
  51. # the last line contains the compiler commandline arguments as some
  52. # projects may compile an extension multiple times with different
  53. # arguments
  54. with open(dep_file) as f:
  55. lines = f.readlines()
  56. cmdline =_commandline_dep_string(cc_args, extra_postargs, pp_opts)
  57. last_cmdline = lines[-1]
  58. if last_cmdline != cmdline:
  59. return True
  60. contents = ''.join(lines[:-1])
  61. deps = [x for x in shlex.split(contents, posix=True)
  62. if x != "\n" and not x.endswith(":")]
  63. try:
  64. t_obj = os.stat(obj).st_mtime
  65. # check if any of the dependencies is newer than the object
  66. # the dependencies includes the source used to create the object
  67. for f in deps:
  68. if os.stat(f).st_mtime > t_obj:
  69. return True
  70. except OSError:
  71. # no object counts as newer (shouldn't happen if dep_file exists)
  72. return True
  73. return False
  74. def replace_method(klass, method_name, func):
  75. # Py3k does not have unbound method anymore, MethodType does not work
  76. m = lambda self, *args, **kw: func(self, *args, **kw)
  77. setattr(klass, method_name, m)
  78. ######################################################################
  79. ## Method that subclasses may redefine. But don't call this method,
  80. ## it i private to CCompiler class and may return unexpected
  81. ## results if used elsewhere. So, you have been warned..
  82. def CCompiler_find_executables(self):
  83. """
  84. Does nothing here, but is called by the get_version method and can be
  85. overridden by subclasses. In particular it is redefined in the `FCompiler`
  86. class where more documentation can be found.
  87. """
  88. pass
  89. replace_method(CCompiler, 'find_executables', CCompiler_find_executables)
  90. # Using customized CCompiler.spawn.
  91. def CCompiler_spawn(self, cmd, display=None, env=None):
  92. """
  93. Execute a command in a sub-process.
  94. Parameters
  95. ----------
  96. cmd : str
  97. The command to execute.
  98. display : str or sequence of str, optional
  99. The text to add to the log file kept by `numpy.distutils`.
  100. If not given, `display` is equal to `cmd`.
  101. env : a dictionary for environment variables, optional
  102. Returns
  103. -------
  104. None
  105. Raises
  106. ------
  107. DistutilsExecError
  108. If the command failed, i.e. the exit status was not 0.
  109. """
  110. env = env if env is not None else dict(os.environ)
  111. if display is None:
  112. display = cmd
  113. if is_sequence(display):
  114. display = ' '.join(list(display))
  115. log.info(display)
  116. try:
  117. if self.verbose:
  118. subprocess.check_output(cmd, env=env)
  119. else:
  120. subprocess.check_output(cmd, stderr=subprocess.STDOUT, env=env)
  121. except subprocess.CalledProcessError as exc:
  122. o = exc.output
  123. s = exc.returncode
  124. except OSError as e:
  125. # OSError doesn't have the same hooks for the exception
  126. # output, but exec_command() historically would use an
  127. # empty string for EnvironmentError (base class for
  128. # OSError)
  129. # o = b''
  130. # still that would make the end-user lost in translation!
  131. o = f"\n\n{e}\n\n\n"
  132. try:
  133. o = o.encode(sys.stdout.encoding)
  134. except AttributeError:
  135. o = o.encode('utf8')
  136. # status previously used by exec_command() for parent
  137. # of OSError
  138. s = 127
  139. else:
  140. # use a convenience return here so that any kind of
  141. # caught exception will execute the default code after the
  142. # try / except block, which handles various exceptions
  143. return None
  144. if is_sequence(cmd):
  145. cmd = ' '.join(list(cmd))
  146. if self.verbose:
  147. forward_bytes_to_stdout(o)
  148. if re.search(b'Too many open files', o):
  149. msg = '\nTry rerunning setup command until build succeeds.'
  150. else:
  151. msg = ''
  152. raise DistutilsExecError('Command "%s" failed with exit status %d%s' %
  153. (cmd, s, msg))
  154. replace_method(CCompiler, 'spawn', CCompiler_spawn)
  155. def CCompiler_object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
  156. """
  157. Return the name of the object files for the given source files.
  158. Parameters
  159. ----------
  160. source_filenames : list of str
  161. The list of paths to source files. Paths can be either relative or
  162. absolute, this is handled transparently.
  163. strip_dir : bool, optional
  164. Whether to strip the directory from the returned paths. If True,
  165. the file name prepended by `output_dir` is returned. Default is False.
  166. output_dir : str, optional
  167. If given, this path is prepended to the returned paths to the
  168. object files.
  169. Returns
  170. -------
  171. obj_names : list of str
  172. The list of paths to the object files corresponding to the source
  173. files in `source_filenames`.
  174. """
  175. if output_dir is None:
  176. output_dir = ''
  177. obj_names = []
  178. for src_name in source_filenames:
  179. base, ext = os.path.splitext(os.path.normpath(src_name))
  180. base = os.path.splitdrive(base)[1] # Chop off the drive
  181. base = base[os.path.isabs(base):] # If abs, chop off leading /
  182. if base.startswith('..'):
  183. # Resolve starting relative path components, middle ones
  184. # (if any) have been handled by os.path.normpath above.
  185. i = base.rfind('..')+2
  186. d = base[:i]
  187. d = os.path.basename(os.path.abspath(d))
  188. base = d + base[i:]
  189. if ext not in self.src_extensions:
  190. raise UnknownFileError("unknown file type '%s' (from '%s')" % (ext, src_name))
  191. if strip_dir:
  192. base = os.path.basename(base)
  193. obj_name = os.path.join(output_dir, base + self.obj_extension)
  194. obj_names.append(obj_name)
  195. return obj_names
  196. replace_method(CCompiler, 'object_filenames', CCompiler_object_filenames)
  197. def CCompiler_compile(self, sources, output_dir=None, macros=None,
  198. include_dirs=None, debug=0, extra_preargs=None,
  199. extra_postargs=None, depends=None):
  200. """
  201. Compile one or more source files.
  202. Please refer to the Python distutils API reference for more details.
  203. Parameters
  204. ----------
  205. sources : list of str
  206. A list of filenames
  207. output_dir : str, optional
  208. Path to the output directory.
  209. macros : list of tuples
  210. A list of macro definitions.
  211. include_dirs : list of str, optional
  212. The directories to add to the default include file search path for
  213. this compilation only.
  214. debug : bool, optional
  215. Whether or not to output debug symbols in or alongside the object
  216. file(s).
  217. extra_preargs, extra_postargs : ?
  218. Extra pre- and post-arguments.
  219. depends : list of str, optional
  220. A list of file names that all targets depend on.
  221. Returns
  222. -------
  223. objects : list of str
  224. A list of object file names, one per source file `sources`.
  225. Raises
  226. ------
  227. CompileError
  228. If compilation fails.
  229. """
  230. global _job_semaphore
  231. jobs = get_num_build_jobs()
  232. # setup semaphore to not exceed number of compile jobs when parallelized at
  233. # extension level (python >= 3.5)
  234. with _global_lock:
  235. if _job_semaphore is None:
  236. _job_semaphore = threading.Semaphore(jobs)
  237. if not sources:
  238. return []
  239. from numpy.distutils.fcompiler import (FCompiler,
  240. FORTRAN_COMMON_FIXED_EXTENSIONS,
  241. has_f90_header)
  242. if isinstance(self, FCompiler):
  243. display = []
  244. for fc in ['f77', 'f90', 'fix']:
  245. fcomp = getattr(self, 'compiler_'+fc)
  246. if fcomp is None:
  247. continue
  248. display.append("Fortran %s compiler: %s" % (fc, ' '.join(fcomp)))
  249. display = '\n'.join(display)
  250. else:
  251. ccomp = self.compiler_so
  252. display = "C compiler: %s\n" % (' '.join(ccomp),)
  253. log.info(display)
  254. macros, objects, extra_postargs, pp_opts, build = \
  255. self._setup_compile(output_dir, macros, include_dirs, sources,
  256. depends, extra_postargs)
  257. cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
  258. display = "compile options: '%s'" % (' '.join(cc_args))
  259. if extra_postargs:
  260. display += "\nextra options: '%s'" % (' '.join(extra_postargs))
  261. log.info(display)
  262. def single_compile(args):
  263. obj, (src, ext) = args
  264. if not _needs_build(obj, cc_args, extra_postargs, pp_opts):
  265. return
  266. # check if we are currently already processing the same object
  267. # happens when using the same source in multiple extensions
  268. while True:
  269. # need explicit lock as there is no atomic check and add with GIL
  270. with _global_lock:
  271. # file not being worked on, start working
  272. if obj not in _processing_files:
  273. _processing_files.add(obj)
  274. break
  275. # wait for the processing to end
  276. time.sleep(0.1)
  277. try:
  278. # retrieve slot from our #job semaphore and build
  279. with _job_semaphore:
  280. self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
  281. finally:
  282. # register being done processing
  283. with _global_lock:
  284. _processing_files.remove(obj)
  285. if isinstance(self, FCompiler):
  286. objects_to_build = list(build.keys())
  287. f77_objects, other_objects = [], []
  288. for obj in objects:
  289. if obj in objects_to_build:
  290. src, ext = build[obj]
  291. if self.compiler_type=='absoft':
  292. obj = cyg2win32(obj)
  293. src = cyg2win32(src)
  294. if Path(src).suffix.lower() in FORTRAN_COMMON_FIXED_EXTENSIONS \
  295. and not has_f90_header(src):
  296. f77_objects.append((obj, (src, ext)))
  297. else:
  298. other_objects.append((obj, (src, ext)))
  299. # f77 objects can be built in parallel
  300. build_items = f77_objects
  301. # build f90 modules serial, module files are generated during
  302. # compilation and may be used by files later in the list so the
  303. # ordering is important
  304. for o in other_objects:
  305. single_compile(o)
  306. else:
  307. build_items = build.items()
  308. if len(build) > 1 and jobs > 1:
  309. # build parallel
  310. from concurrent.futures import ThreadPoolExecutor
  311. with ThreadPoolExecutor(jobs) as pool:
  312. res = pool.map(single_compile, build_items)
  313. list(res) # access result to raise errors
  314. else:
  315. # build serial
  316. for o in build_items:
  317. single_compile(o)
  318. # Return *all* object filenames, not just the ones we just built.
  319. return objects
  320. replace_method(CCompiler, 'compile', CCompiler_compile)
  321. def CCompiler_customize_cmd(self, cmd, ignore=()):
  322. """
  323. Customize compiler using distutils command.
  324. Parameters
  325. ----------
  326. cmd : class instance
  327. An instance inheriting from ``distutils.cmd.Command``.
  328. ignore : sequence of str, optional
  329. List of ``distutils.ccompiler.CCompiler`` commands (without ``'set_'``) that should not be
  330. altered. Strings that are checked for are:
  331. ``('include_dirs', 'define', 'undef', 'libraries', 'library_dirs',
  332. 'rpath', 'link_objects')``.
  333. Returns
  334. -------
  335. None
  336. """
  337. log.info('customize %s using %s' % (self.__class__.__name__,
  338. cmd.__class__.__name__))
  339. if (
  340. hasattr(self, 'compiler') and
  341. 'clang' in self.compiler[0] and
  342. not (platform.machine() == 'arm64' and sys.platform == 'darwin')
  343. ):
  344. # clang defaults to a non-strict floating error point model.
  345. # However, '-ftrapping-math' is not currently supported (2023-04-08)
  346. # for macosx_arm64.
  347. # Since NumPy and most Python libs give warnings for these, override:
  348. self.compiler.append('-ftrapping-math')
  349. self.compiler_so.append('-ftrapping-math')
  350. def allow(attr):
  351. return getattr(cmd, attr, None) is not None and attr not in ignore
  352. if allow('include_dirs'):
  353. self.set_include_dirs(cmd.include_dirs)
  354. if allow('define'):
  355. for (name, value) in cmd.define:
  356. self.define_macro(name, value)
  357. if allow('undef'):
  358. for macro in cmd.undef:
  359. self.undefine_macro(macro)
  360. if allow('libraries'):
  361. self.set_libraries(self.libraries + cmd.libraries)
  362. if allow('library_dirs'):
  363. self.set_library_dirs(self.library_dirs + cmd.library_dirs)
  364. if allow('rpath'):
  365. self.set_runtime_library_dirs(cmd.rpath)
  366. if allow('link_objects'):
  367. self.set_link_objects(cmd.link_objects)
  368. replace_method(CCompiler, 'customize_cmd', CCompiler_customize_cmd)
  369. def _compiler_to_string(compiler):
  370. props = []
  371. mx = 0
  372. keys = list(compiler.executables.keys())
  373. for key in ['version', 'libraries', 'library_dirs',
  374. 'object_switch', 'compile_switch',
  375. 'include_dirs', 'define', 'undef', 'rpath', 'link_objects']:
  376. if key not in keys:
  377. keys.append(key)
  378. for key in keys:
  379. if hasattr(compiler, key):
  380. v = getattr(compiler, key)
  381. mx = max(mx, len(key))
  382. props.append((key, repr(v)))
  383. fmt = '%-' + repr(mx+1) + 's = %s'
  384. lines = [fmt % prop for prop in props]
  385. return '\n'.join(lines)
  386. def CCompiler_show_customization(self):
  387. """
  388. Print the compiler customizations to stdout.
  389. Parameters
  390. ----------
  391. None
  392. Returns
  393. -------
  394. None
  395. Notes
  396. -----
  397. Printing is only done if the distutils log threshold is < 2.
  398. """
  399. try:
  400. self.get_version()
  401. except Exception:
  402. pass
  403. if log._global_log.threshold<2:
  404. print('*'*80)
  405. print(self.__class__)
  406. print(_compiler_to_string(self))
  407. print('*'*80)
  408. replace_method(CCompiler, 'show_customization', CCompiler_show_customization)
  409. def CCompiler_customize(self, dist, need_cxx=0):
  410. """
  411. Do any platform-specific customization of a compiler instance.
  412. This method calls ``distutils.sysconfig.customize_compiler`` for
  413. platform-specific customization, as well as optionally remove a flag
  414. to suppress spurious warnings in case C++ code is being compiled.
  415. Parameters
  416. ----------
  417. dist : object
  418. This parameter is not used for anything.
  419. need_cxx : bool, optional
  420. Whether or not C++ has to be compiled. If so (True), the
  421. ``"-Wstrict-prototypes"`` option is removed to prevent spurious
  422. warnings. Default is False.
  423. Returns
  424. -------
  425. None
  426. Notes
  427. -----
  428. All the default options used by distutils can be extracted with::
  429. from distutils import sysconfig
  430. sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'BASECFLAGS',
  431. 'CCSHARED', 'LDSHARED', 'SO')
  432. """
  433. # See FCompiler.customize for suggested usage.
  434. log.info('customize %s' % (self.__class__.__name__))
  435. customize_compiler(self)
  436. if need_cxx:
  437. # In general, distutils uses -Wstrict-prototypes, but this option is
  438. # not valid for C++ code, only for C. Remove it if it's there to
  439. # avoid a spurious warning on every compilation.
  440. try:
  441. self.compiler_so.remove('-Wstrict-prototypes')
  442. except (AttributeError, ValueError):
  443. pass
  444. if hasattr(self, 'compiler') and 'cc' in self.compiler[0]:
  445. if not self.compiler_cxx:
  446. if self.compiler[0].startswith('gcc'):
  447. a, b = 'gcc', 'g++'
  448. else:
  449. a, b = 'cc', 'c++'
  450. self.compiler_cxx = [self.compiler[0].replace(a, b)]\
  451. + self.compiler[1:]
  452. else:
  453. if hasattr(self, 'compiler'):
  454. log.warn("#### %s #######" % (self.compiler,))
  455. if not hasattr(self, 'compiler_cxx'):
  456. log.warn('Missing compiler_cxx fix for ' + self.__class__.__name__)
  457. # check if compiler supports gcc style automatic dependencies
  458. # run on every extension so skip for known good compilers
  459. if hasattr(self, 'compiler') and ('gcc' in self.compiler[0] or
  460. 'g++' in self.compiler[0] or
  461. 'clang' in self.compiler[0]):
  462. self._auto_depends = True
  463. elif os.name == 'posix':
  464. import tempfile
  465. import shutil
  466. tmpdir = tempfile.mkdtemp()
  467. try:
  468. fn = os.path.join(tmpdir, "file.c")
  469. with open(fn, "w") as f:
  470. f.write("int a;\n")
  471. self.compile([fn], output_dir=tmpdir,
  472. extra_preargs=['-MMD', '-MF', fn + '.d'])
  473. self._auto_depends = True
  474. except CompileError:
  475. self._auto_depends = False
  476. finally:
  477. shutil.rmtree(tmpdir)
  478. return
  479. replace_method(CCompiler, 'customize', CCompiler_customize)
  480. def simple_version_match(pat=r'[-.\d]+', ignore='', start=''):
  481. """
  482. Simple matching of version numbers, for use in CCompiler and FCompiler.
  483. Parameters
  484. ----------
  485. pat : str, optional
  486. A regular expression matching version numbers.
  487. Default is ``r'[-.\\d]+'``.
  488. ignore : str, optional
  489. A regular expression matching patterns to skip.
  490. Default is ``''``, in which case nothing is skipped.
  491. start : str, optional
  492. A regular expression matching the start of where to start looking
  493. for version numbers.
  494. Default is ``''``, in which case searching is started at the
  495. beginning of the version string given to `matcher`.
  496. Returns
  497. -------
  498. matcher : callable
  499. A function that is appropriate to use as the ``.version_match``
  500. attribute of a ``distutils.ccompiler.CCompiler`` class. `matcher` takes a single parameter,
  501. a version string.
  502. """
  503. def matcher(self, version_string):
  504. # version string may appear in the second line, so getting rid
  505. # of new lines:
  506. version_string = version_string.replace('\n', ' ')
  507. pos = 0
  508. if start:
  509. m = re.match(start, version_string)
  510. if not m:
  511. return None
  512. pos = m.end()
  513. while True:
  514. m = re.search(pat, version_string[pos:])
  515. if not m:
  516. return None
  517. if ignore and re.match(ignore, m.group(0)):
  518. pos = m.end()
  519. continue
  520. break
  521. return m.group(0)
  522. return matcher
  523. def CCompiler_get_version(self, force=False, ok_status=[0]):
  524. """
  525. Return compiler version, or None if compiler is not available.
  526. Parameters
  527. ----------
  528. force : bool, optional
  529. If True, force a new determination of the version, even if the
  530. compiler already has a version attribute. Default is False.
  531. ok_status : list of int, optional
  532. The list of status values returned by the version look-up process
  533. for which a version string is returned. If the status value is not
  534. in `ok_status`, None is returned. Default is ``[0]``.
  535. Returns
  536. -------
  537. version : str or None
  538. Version string, in the format of ``distutils.version.LooseVersion``.
  539. """
  540. if not force and hasattr(self, 'version'):
  541. return self.version
  542. self.find_executables()
  543. try:
  544. version_cmd = self.version_cmd
  545. except AttributeError:
  546. return None
  547. if not version_cmd or not version_cmd[0]:
  548. return None
  549. try:
  550. matcher = self.version_match
  551. except AttributeError:
  552. try:
  553. pat = self.version_pattern
  554. except AttributeError:
  555. return None
  556. def matcher(version_string):
  557. m = re.match(pat, version_string)
  558. if not m:
  559. return None
  560. version = m.group('version')
  561. return version
  562. try:
  563. output = subprocess.check_output(version_cmd, stderr=subprocess.STDOUT)
  564. except subprocess.CalledProcessError as exc:
  565. output = exc.output
  566. status = exc.returncode
  567. except OSError:
  568. # match the historical returns for a parent
  569. # exception class caught by exec_command()
  570. status = 127
  571. output = b''
  572. else:
  573. # output isn't actually a filepath but we do this
  574. # for now to match previous distutils behavior
  575. output = filepath_from_subprocess_output(output)
  576. status = 0
  577. version = None
  578. if status in ok_status:
  579. version = matcher(output)
  580. if version:
  581. version = LooseVersion(version)
  582. self.version = version
  583. return version
  584. replace_method(CCompiler, 'get_version', CCompiler_get_version)
  585. def CCompiler_cxx_compiler(self):
  586. """
  587. Return the C++ compiler.
  588. Parameters
  589. ----------
  590. None
  591. Returns
  592. -------
  593. cxx : class instance
  594. The C++ compiler, as a ``distutils.ccompiler.CCompiler`` instance.
  595. """
  596. if self.compiler_type in ('msvc', 'intelw', 'intelemw'):
  597. return self
  598. cxx = copy(self)
  599. cxx.compiler_cxx = cxx.compiler_cxx
  600. cxx.compiler_so = [cxx.compiler_cxx[0]] + \
  601. sanitize_cxx_flags(cxx.compiler_so[1:])
  602. if (sys.platform.startswith(('aix', 'os400')) and
  603. 'ld_so_aix' in cxx.linker_so[0]):
  604. # AIX needs the ld_so_aix script included with Python
  605. cxx.linker_so = [cxx.linker_so[0], cxx.compiler_cxx[0]] \
  606. + cxx.linker_so[2:]
  607. if sys.platform.startswith('os400'):
  608. #This is required by i 7.4 and prievous for PRId64 in printf() call.
  609. cxx.compiler_so.append('-D__STDC_FORMAT_MACROS')
  610. #This a bug of gcc10.3, which failed to handle the TLS init.
  611. cxx.compiler_so.append('-fno-extern-tls-init')
  612. cxx.linker_so.append('-fno-extern-tls-init')
  613. else:
  614. cxx.linker_so = [cxx.compiler_cxx[0]] + cxx.linker_so[1:]
  615. return cxx
  616. replace_method(CCompiler, 'cxx_compiler', CCompiler_cxx_compiler)
  617. compiler_class['intel'] = ('intelccompiler', 'IntelCCompiler',
  618. "Intel C Compiler for 32-bit applications")
  619. compiler_class['intele'] = ('intelccompiler', 'IntelItaniumCCompiler',
  620. "Intel C Itanium Compiler for Itanium-based applications")
  621. compiler_class['intelem'] = ('intelccompiler', 'IntelEM64TCCompiler',
  622. "Intel C Compiler for 64-bit applications")
  623. compiler_class['intelw'] = ('intelccompiler', 'IntelCCompilerW',
  624. "Intel C Compiler for 32-bit applications on Windows")
  625. compiler_class['intelemw'] = ('intelccompiler', 'IntelEM64TCCompilerW',
  626. "Intel C Compiler for 64-bit applications on Windows")
  627. compiler_class['pathcc'] = ('pathccompiler', 'PathScaleCCompiler',
  628. "PathScale Compiler for SiCortex-based applications")
  629. compiler_class['arm'] = ('armccompiler', 'ArmCCompiler',
  630. "Arm C Compiler")
  631. compiler_class['fujitsu'] = ('fujitsuccompiler', 'FujitsuCCompiler',
  632. "Fujitsu C Compiler")
  633. ccompiler._default_compilers += (('linux.*', 'intel'),
  634. ('linux.*', 'intele'),
  635. ('linux.*', 'intelem'),
  636. ('linux.*', 'pathcc'),
  637. ('nt', 'intelw'),
  638. ('nt', 'intelemw'))
  639. if sys.platform == 'win32':
  640. compiler_class['mingw32'] = ('mingw32ccompiler', 'Mingw32CCompiler',
  641. "Mingw32 port of GNU C Compiler for Win32"\
  642. "(for MSC built Python)")
  643. if mingw32():
  644. # On windows platforms, we want to default to mingw32 (gcc)
  645. # because msvc can't build blitz stuff.
  646. log.info('Setting mingw32 as default compiler for nt.')
  647. ccompiler._default_compilers = (('nt', 'mingw32'),) \
  648. + ccompiler._default_compilers
  649. _distutils_new_compiler = new_compiler
  650. def new_compiler (plat=None,
  651. compiler=None,
  652. verbose=None,
  653. dry_run=0,
  654. force=0):
  655. # Try first C compilers from numpy.distutils.
  656. if verbose is None:
  657. verbose = log.get_threshold() <= log.INFO
  658. if plat is None:
  659. plat = os.name
  660. try:
  661. if compiler is None:
  662. compiler = get_default_compiler(plat)
  663. (module_name, class_name, long_description) = compiler_class[compiler]
  664. except KeyError:
  665. msg = "don't know how to compile C/C++ code on platform '%s'" % plat
  666. if compiler is not None:
  667. msg = msg + " with '%s' compiler" % compiler
  668. raise DistutilsPlatformError(msg)
  669. module_name = "numpy.distutils." + module_name
  670. try:
  671. __import__ (module_name)
  672. except ImportError as e:
  673. msg = str(e)
  674. log.info('%s in numpy.distutils; trying from distutils',
  675. str(msg))
  676. module_name = module_name[6:]
  677. try:
  678. __import__(module_name)
  679. except ImportError as e:
  680. msg = str(e)
  681. raise DistutilsModuleError("can't compile C/C++ code: unable to load module '%s'" % \
  682. module_name)
  683. try:
  684. module = sys.modules[module_name]
  685. klass = vars(module)[class_name]
  686. except KeyError:
  687. raise DistutilsModuleError(("can't compile C/C++ code: unable to find class '%s' " +
  688. "in module '%s'") % (class_name, module_name))
  689. compiler = klass(None, dry_run, force)
  690. compiler.verbose = verbose
  691. log.debug('new_compiler returns %s' % (klass))
  692. return compiler
  693. ccompiler.new_compiler = new_compiler
  694. _distutils_gen_lib_options = gen_lib_options
  695. def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
  696. # the version of this function provided by CPython allows the following
  697. # to return lists, which are unpacked automatically:
  698. # - compiler.runtime_library_dir_option
  699. # our version extends the behavior to:
  700. # - compiler.library_dir_option
  701. # - compiler.library_option
  702. # - compiler.find_library_file
  703. r = _distutils_gen_lib_options(compiler, library_dirs,
  704. runtime_library_dirs, libraries)
  705. lib_opts = []
  706. for i in r:
  707. if is_sequence(i):
  708. lib_opts.extend(list(i))
  709. else:
  710. lib_opts.append(i)
  711. return lib_opts
  712. ccompiler.gen_lib_options = gen_lib_options
  713. # Also fix up the various compiler modules, which do
  714. # from distutils.ccompiler import gen_lib_options
  715. # Don't bother with mwerks, as we don't support Classic Mac.
  716. for _cc in ['msvc9', 'msvc', '_msvc', 'bcpp', 'cygwinc', 'emxc', 'unixc']:
  717. _m = sys.modules.get('distutils.' + _cc + 'compiler')
  718. if _m is not None:
  719. setattr(_m, 'gen_lib_options', gen_lib_options)