build_ext.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752
  1. """ Modified version of build_ext that handles fortran source files.
  2. """
  3. import os
  4. import subprocess
  5. from glob import glob
  6. from distutils.dep_util import newer_group
  7. from distutils.command.build_ext import build_ext as old_build_ext
  8. from distutils.errors import DistutilsFileError, DistutilsSetupError,\
  9. DistutilsError
  10. from distutils.file_util import copy_file
  11. from numpy.distutils import log
  12. from numpy.distutils.exec_command import filepath_from_subprocess_output
  13. from numpy.distutils.system_info import combine_paths
  14. from numpy.distutils.misc_util import (
  15. filter_sources, get_ext_source_files, get_numpy_include_dirs,
  16. has_cxx_sources, has_f_sources, is_sequence
  17. )
  18. from numpy.distutils.command.config_compiler import show_fortran_compilers
  19. from numpy.distutils.ccompiler_opt import new_ccompiler_opt, CCompilerOpt
  20. class build_ext (old_build_ext):
  21. description = "build C/C++/F extensions (compile/link to build directory)"
  22. user_options = old_build_ext.user_options + [
  23. ('fcompiler=', None,
  24. "specify the Fortran compiler type"),
  25. ('parallel=', 'j',
  26. "number of parallel jobs"),
  27. ('warn-error', None,
  28. "turn all warnings into errors (-Werror)"),
  29. ('cpu-baseline=', None,
  30. "specify a list of enabled baseline CPU optimizations"),
  31. ('cpu-dispatch=', None,
  32. "specify a list of dispatched CPU optimizations"),
  33. ('disable-optimization', None,
  34. "disable CPU optimized code(dispatch,simd,fast...)"),
  35. ('simd-test=', None,
  36. "specify a list of CPU optimizations to be tested against NumPy SIMD interface"),
  37. ]
  38. help_options = old_build_ext.help_options + [
  39. ('help-fcompiler', None, "list available Fortran compilers",
  40. show_fortran_compilers),
  41. ]
  42. boolean_options = old_build_ext.boolean_options + ['warn-error', 'disable-optimization']
  43. def initialize_options(self):
  44. old_build_ext.initialize_options(self)
  45. self.fcompiler = None
  46. self.parallel = None
  47. self.warn_error = None
  48. self.cpu_baseline = None
  49. self.cpu_dispatch = None
  50. self.disable_optimization = None
  51. self.simd_test = None
  52. def finalize_options(self):
  53. if self.parallel:
  54. try:
  55. self.parallel = int(self.parallel)
  56. except ValueError as e:
  57. raise ValueError("--parallel/-j argument must be an integer") from e
  58. # Ensure that self.include_dirs and self.distribution.include_dirs
  59. # refer to the same list object. finalize_options will modify
  60. # self.include_dirs, but self.distribution.include_dirs is used
  61. # during the actual build.
  62. # self.include_dirs is None unless paths are specified with
  63. # --include-dirs.
  64. # The include paths will be passed to the compiler in the order:
  65. # numpy paths, --include-dirs paths, Python include path.
  66. if isinstance(self.include_dirs, str):
  67. self.include_dirs = self.include_dirs.split(os.pathsep)
  68. incl_dirs = self.include_dirs or []
  69. if self.distribution.include_dirs is None:
  70. self.distribution.include_dirs = []
  71. self.include_dirs = self.distribution.include_dirs
  72. self.include_dirs.extend(incl_dirs)
  73. old_build_ext.finalize_options(self)
  74. self.set_undefined_options('build',
  75. ('parallel', 'parallel'),
  76. ('warn_error', 'warn_error'),
  77. ('cpu_baseline', 'cpu_baseline'),
  78. ('cpu_dispatch', 'cpu_dispatch'),
  79. ('disable_optimization', 'disable_optimization'),
  80. ('simd_test', 'simd_test')
  81. )
  82. CCompilerOpt.conf_target_groups["simd_test"] = self.simd_test
  83. def run(self):
  84. if not self.extensions:
  85. return
  86. # Make sure that extension sources are complete.
  87. self.run_command('build_src')
  88. if self.distribution.has_c_libraries():
  89. if self.inplace:
  90. if self.distribution.have_run.get('build_clib'):
  91. log.warn('build_clib already run, it is too late to '
  92. 'ensure in-place build of build_clib')
  93. build_clib = self.distribution.get_command_obj(
  94. 'build_clib')
  95. else:
  96. build_clib = self.distribution.get_command_obj(
  97. 'build_clib')
  98. build_clib.inplace = 1
  99. build_clib.ensure_finalized()
  100. build_clib.run()
  101. self.distribution.have_run['build_clib'] = 1
  102. else:
  103. self.run_command('build_clib')
  104. build_clib = self.get_finalized_command('build_clib')
  105. self.library_dirs.append(build_clib.build_clib)
  106. else:
  107. build_clib = None
  108. # Not including C libraries to the list of
  109. # extension libraries automatically to prevent
  110. # bogus linking commands. Extensions must
  111. # explicitly specify the C libraries that they use.
  112. from distutils.ccompiler import new_compiler
  113. from numpy.distutils.fcompiler import new_fcompiler
  114. compiler_type = self.compiler
  115. # Initialize C compiler:
  116. self.compiler = new_compiler(compiler=compiler_type,
  117. verbose=self.verbose,
  118. dry_run=self.dry_run,
  119. force=self.force)
  120. self.compiler.customize(self.distribution)
  121. self.compiler.customize_cmd(self)
  122. if self.warn_error:
  123. self.compiler.compiler.append('-Werror')
  124. self.compiler.compiler_so.append('-Werror')
  125. self.compiler.show_customization()
  126. if not self.disable_optimization:
  127. dispatch_hpath = os.path.join("numpy", "distutils", "include", "npy_cpu_dispatch_config.h")
  128. dispatch_hpath = os.path.join(self.get_finalized_command("build_src").build_src, dispatch_hpath)
  129. opt_cache_path = os.path.abspath(
  130. os.path.join(self.build_temp, 'ccompiler_opt_cache_ext.py')
  131. )
  132. if hasattr(self, "compiler_opt"):
  133. # By default `CCompilerOpt` update the cache at the exit of
  134. # the process, which may lead to duplicate building
  135. # (see build_extension()/force_rebuild) if run() called
  136. # multiple times within the same os process/thread without
  137. # giving the chance the previous instances of `CCompilerOpt`
  138. # to update the cache.
  139. self.compiler_opt.cache_flush()
  140. self.compiler_opt = new_ccompiler_opt(
  141. compiler=self.compiler, dispatch_hpath=dispatch_hpath,
  142. cpu_baseline=self.cpu_baseline, cpu_dispatch=self.cpu_dispatch,
  143. cache_path=opt_cache_path
  144. )
  145. def report(copt):
  146. log.info("\n########### EXT COMPILER OPTIMIZATION ###########")
  147. log.info(copt.report(full=True))
  148. import atexit
  149. atexit.register(report, self.compiler_opt)
  150. # Setup directory for storing generated extra DLL files on Windows
  151. self.extra_dll_dir = os.path.join(self.build_temp, '.libs')
  152. if not os.path.isdir(self.extra_dll_dir):
  153. os.makedirs(self.extra_dll_dir)
  154. # Create mapping of libraries built by build_clib:
  155. clibs = {}
  156. if build_clib is not None:
  157. for libname, build_info in build_clib.libraries or []:
  158. if libname in clibs and clibs[libname] != build_info:
  159. log.warn('library %r defined more than once,'
  160. ' overwriting build_info\n%s... \nwith\n%s...'
  161. % (libname, repr(clibs[libname])[:300], repr(build_info)[:300]))
  162. clibs[libname] = build_info
  163. # .. and distribution libraries:
  164. for libname, build_info in self.distribution.libraries or []:
  165. if libname in clibs:
  166. # build_clib libraries have a precedence before distribution ones
  167. continue
  168. clibs[libname] = build_info
  169. # Determine if C++/Fortran 77/Fortran 90 compilers are needed.
  170. # Update extension libraries, library_dirs, and macros.
  171. all_languages = set()
  172. for ext in self.extensions:
  173. ext_languages = set()
  174. c_libs = []
  175. c_lib_dirs = []
  176. macros = []
  177. for libname in ext.libraries:
  178. if libname in clibs:
  179. binfo = clibs[libname]
  180. c_libs += binfo.get('libraries', [])
  181. c_lib_dirs += binfo.get('library_dirs', [])
  182. for m in binfo.get('macros', []):
  183. if m not in macros:
  184. macros.append(m)
  185. for l in clibs.get(libname, {}).get('source_languages', []):
  186. ext_languages.add(l)
  187. if c_libs:
  188. new_c_libs = ext.libraries + c_libs
  189. log.info('updating extension %r libraries from %r to %r'
  190. % (ext.name, ext.libraries, new_c_libs))
  191. ext.libraries = new_c_libs
  192. ext.library_dirs = ext.library_dirs + c_lib_dirs
  193. if macros:
  194. log.info('extending extension %r defined_macros with %r'
  195. % (ext.name, macros))
  196. ext.define_macros = ext.define_macros + macros
  197. # determine extension languages
  198. if has_f_sources(ext.sources):
  199. ext_languages.add('f77')
  200. if has_cxx_sources(ext.sources):
  201. ext_languages.add('c++')
  202. l = ext.language or self.compiler.detect_language(ext.sources)
  203. if l:
  204. ext_languages.add(l)
  205. # reset language attribute for choosing proper linker
  206. #
  207. # When we build extensions with multiple languages, we have to
  208. # choose a linker. The rules here are:
  209. # 1. if there is Fortran code, always prefer the Fortran linker,
  210. # 2. otherwise prefer C++ over C,
  211. # 3. Users can force a particular linker by using
  212. # `language='c'` # or 'c++', 'f90', 'f77'
  213. # in their config.add_extension() calls.
  214. if 'c++' in ext_languages:
  215. ext_language = 'c++'
  216. else:
  217. ext_language = 'c' # default
  218. has_fortran = False
  219. if 'f90' in ext_languages:
  220. ext_language = 'f90'
  221. has_fortran = True
  222. elif 'f77' in ext_languages:
  223. ext_language = 'f77'
  224. has_fortran = True
  225. if not ext.language or has_fortran:
  226. if l and l != ext_language and ext.language:
  227. log.warn('resetting extension %r language from %r to %r.' %
  228. (ext.name, l, ext_language))
  229. ext.language = ext_language
  230. # global language
  231. all_languages.update(ext_languages)
  232. need_f90_compiler = 'f90' in all_languages
  233. need_f77_compiler = 'f77' in all_languages
  234. need_cxx_compiler = 'c++' in all_languages
  235. # Initialize C++ compiler:
  236. if need_cxx_compiler:
  237. self._cxx_compiler = new_compiler(compiler=compiler_type,
  238. verbose=self.verbose,
  239. dry_run=self.dry_run,
  240. force=self.force)
  241. compiler = self._cxx_compiler
  242. compiler.customize(self.distribution, need_cxx=need_cxx_compiler)
  243. compiler.customize_cmd(self)
  244. compiler.show_customization()
  245. self._cxx_compiler = compiler.cxx_compiler()
  246. else:
  247. self._cxx_compiler = None
  248. # Initialize Fortran 77 compiler:
  249. if need_f77_compiler:
  250. ctype = self.fcompiler
  251. self._f77_compiler = new_fcompiler(compiler=self.fcompiler,
  252. verbose=self.verbose,
  253. dry_run=self.dry_run,
  254. force=self.force,
  255. requiref90=False,
  256. c_compiler=self.compiler)
  257. fcompiler = self._f77_compiler
  258. if fcompiler:
  259. ctype = fcompiler.compiler_type
  260. fcompiler.customize(self.distribution)
  261. if fcompiler and fcompiler.get_version():
  262. fcompiler.customize_cmd(self)
  263. fcompiler.show_customization()
  264. else:
  265. self.warn('f77_compiler=%s is not available.' %
  266. (ctype))
  267. self._f77_compiler = None
  268. else:
  269. self._f77_compiler = None
  270. # Initialize Fortran 90 compiler:
  271. if need_f90_compiler:
  272. ctype = self.fcompiler
  273. self._f90_compiler = new_fcompiler(compiler=self.fcompiler,
  274. verbose=self.verbose,
  275. dry_run=self.dry_run,
  276. force=self.force,
  277. requiref90=True,
  278. c_compiler=self.compiler)
  279. fcompiler = self._f90_compiler
  280. if fcompiler:
  281. ctype = fcompiler.compiler_type
  282. fcompiler.customize(self.distribution)
  283. if fcompiler and fcompiler.get_version():
  284. fcompiler.customize_cmd(self)
  285. fcompiler.show_customization()
  286. else:
  287. self.warn('f90_compiler=%s is not available.' %
  288. (ctype))
  289. self._f90_compiler = None
  290. else:
  291. self._f90_compiler = None
  292. # Build extensions
  293. self.build_extensions()
  294. # Copy over any extra DLL files
  295. # FIXME: In the case where there are more than two packages,
  296. # we blindly assume that both packages need all of the libraries,
  297. # resulting in a larger wheel than is required. This should be fixed,
  298. # but it's so rare that I won't bother to handle it.
  299. pkg_roots = {
  300. self.get_ext_fullname(ext.name).split('.')[0]
  301. for ext in self.extensions
  302. }
  303. for pkg_root in pkg_roots:
  304. shared_lib_dir = os.path.join(pkg_root, '.libs')
  305. if not self.inplace:
  306. shared_lib_dir = os.path.join(self.build_lib, shared_lib_dir)
  307. for fn in os.listdir(self.extra_dll_dir):
  308. if not os.path.isdir(shared_lib_dir):
  309. os.makedirs(shared_lib_dir)
  310. if not fn.lower().endswith('.dll'):
  311. continue
  312. runtime_lib = os.path.join(self.extra_dll_dir, fn)
  313. copy_file(runtime_lib, shared_lib_dir)
  314. def swig_sources(self, sources, extensions=None):
  315. # Do nothing. Swig sources have been handled in build_src command.
  316. return sources
  317. def build_extension(self, ext):
  318. sources = ext.sources
  319. if sources is None or not is_sequence(sources):
  320. raise DistutilsSetupError(
  321. ("in 'ext_modules' option (extension '%s'), " +
  322. "'sources' must be present and must be " +
  323. "a list of source filenames") % ext.name)
  324. sources = list(sources)
  325. if not sources:
  326. return
  327. fullname = self.get_ext_fullname(ext.name)
  328. if self.inplace:
  329. modpath = fullname.split('.')
  330. package = '.'.join(modpath[0:-1])
  331. base = modpath[-1]
  332. build_py = self.get_finalized_command('build_py')
  333. package_dir = build_py.get_package_dir(package)
  334. ext_filename = os.path.join(package_dir,
  335. self.get_ext_filename(base))
  336. else:
  337. ext_filename = os.path.join(self.build_lib,
  338. self.get_ext_filename(fullname))
  339. depends = sources + ext.depends
  340. force_rebuild = self.force
  341. if not self.disable_optimization and not self.compiler_opt.is_cached():
  342. log.debug("Detected changes on compiler optimizations")
  343. force_rebuild = True
  344. if not (force_rebuild or newer_group(depends, ext_filename, 'newer')):
  345. log.debug("skipping '%s' extension (up-to-date)", ext.name)
  346. return
  347. else:
  348. log.info("building '%s' extension", ext.name)
  349. extra_args = ext.extra_compile_args or []
  350. extra_cflags = getattr(ext, 'extra_c_compile_args', None) or []
  351. extra_cxxflags = getattr(ext, 'extra_cxx_compile_args', None) or []
  352. macros = ext.define_macros[:]
  353. for undef in ext.undef_macros:
  354. macros.append((undef,))
  355. c_sources, cxx_sources, f_sources, fmodule_sources = \
  356. filter_sources(ext.sources)
  357. if self.compiler.compiler_type == 'msvc':
  358. if cxx_sources:
  359. # Needed to compile kiva.agg._agg extension.
  360. extra_args.append('/Zm1000')
  361. extra_cflags += extra_cxxflags
  362. # this hack works around the msvc compiler attributes
  363. # problem, msvc uses its own convention :(
  364. c_sources += cxx_sources
  365. cxx_sources = []
  366. # Set Fortran/C++ compilers for compilation and linking.
  367. if ext.language == 'f90':
  368. fcompiler = self._f90_compiler
  369. elif ext.language == 'f77':
  370. fcompiler = self._f77_compiler
  371. else: # in case ext.language is c++, for instance
  372. fcompiler = self._f90_compiler or self._f77_compiler
  373. if fcompiler is not None:
  374. fcompiler.extra_f77_compile_args = (ext.extra_f77_compile_args or []) if hasattr(
  375. ext, 'extra_f77_compile_args') else []
  376. fcompiler.extra_f90_compile_args = (ext.extra_f90_compile_args or []) if hasattr(
  377. ext, 'extra_f90_compile_args') else []
  378. cxx_compiler = self._cxx_compiler
  379. # check for the availability of required compilers
  380. if cxx_sources and cxx_compiler is None:
  381. raise DistutilsError("extension %r has C++ sources"
  382. "but no C++ compiler found" % (ext.name))
  383. if (f_sources or fmodule_sources) and fcompiler is None:
  384. raise DistutilsError("extension %r has Fortran sources "
  385. "but no Fortran compiler found" % (ext.name))
  386. if ext.language in ['f77', 'f90'] and fcompiler is None:
  387. self.warn("extension %r has Fortran libraries "
  388. "but no Fortran linker found, using default linker" % (ext.name))
  389. if ext.language == 'c++' and cxx_compiler is None:
  390. self.warn("extension %r has C++ libraries "
  391. "but no C++ linker found, using default linker" % (ext.name))
  392. kws = {'depends': ext.depends}
  393. output_dir = self.build_temp
  394. include_dirs = ext.include_dirs + get_numpy_include_dirs()
  395. # filtering C dispatch-table sources when optimization is not disabled,
  396. # otherwise treated as normal sources.
  397. copt_c_sources = []
  398. copt_cxx_sources = []
  399. copt_baseline_flags = []
  400. copt_macros = []
  401. if not self.disable_optimization:
  402. bsrc_dir = self.get_finalized_command("build_src").build_src
  403. dispatch_hpath = os.path.join("numpy", "distutils", "include")
  404. dispatch_hpath = os.path.join(bsrc_dir, dispatch_hpath)
  405. include_dirs.append(dispatch_hpath)
  406. # copt_build_src = None if self.inplace else bsrc_dir
  407. # Always generate the generated config files and
  408. # dispatch-able sources inside the build directory,
  409. # even if the build option `inplace` is enabled.
  410. # This approach prevents conflicts with Meson-generated
  411. # config headers. Since `spin build --clean` will not remove
  412. # these headers, they might overwrite the generated Meson headers,
  413. # causing compatibility issues. Maintaining separate directories
  414. # ensures compatibility between distutils dispatch config headers
  415. # and Meson headers, avoiding build disruptions.
  416. # See gh-24450 for more details.
  417. copt_build_src = bsrc_dir
  418. for _srcs, _dst, _ext in (
  419. ((c_sources,), copt_c_sources, ('.dispatch.c',)),
  420. ((c_sources, cxx_sources), copt_cxx_sources,
  421. ('.dispatch.cpp', '.dispatch.cxx'))
  422. ):
  423. for _src in _srcs:
  424. _dst += [
  425. _src.pop(_src.index(s))
  426. for s in _src[:] if s.endswith(_ext)
  427. ]
  428. copt_baseline_flags = self.compiler_opt.cpu_baseline_flags()
  429. else:
  430. copt_macros.append(("NPY_DISABLE_OPTIMIZATION", 1))
  431. c_objects = []
  432. if copt_cxx_sources:
  433. log.info("compiling C++ dispatch-able sources")
  434. c_objects += self.compiler_opt.try_dispatch(
  435. copt_cxx_sources,
  436. output_dir=output_dir,
  437. src_dir=copt_build_src,
  438. macros=macros + copt_macros,
  439. include_dirs=include_dirs,
  440. debug=self.debug,
  441. extra_postargs=extra_args + extra_cxxflags,
  442. ccompiler=cxx_compiler,
  443. **kws
  444. )
  445. if copt_c_sources:
  446. log.info("compiling C dispatch-able sources")
  447. c_objects += self.compiler_opt.try_dispatch(
  448. copt_c_sources,
  449. output_dir=output_dir,
  450. src_dir=copt_build_src,
  451. macros=macros + copt_macros,
  452. include_dirs=include_dirs,
  453. debug=self.debug,
  454. extra_postargs=extra_args + extra_cflags,
  455. **kws)
  456. if c_sources:
  457. log.info("compiling C sources")
  458. c_objects += self.compiler.compile(
  459. c_sources,
  460. output_dir=output_dir,
  461. macros=macros + copt_macros,
  462. include_dirs=include_dirs,
  463. debug=self.debug,
  464. extra_postargs=(extra_args + copt_baseline_flags +
  465. extra_cflags),
  466. **kws)
  467. if cxx_sources:
  468. log.info("compiling C++ sources")
  469. c_objects += cxx_compiler.compile(
  470. cxx_sources,
  471. output_dir=output_dir,
  472. macros=macros + copt_macros,
  473. include_dirs=include_dirs,
  474. debug=self.debug,
  475. extra_postargs=(extra_args + copt_baseline_flags +
  476. extra_cxxflags),
  477. **kws)
  478. extra_postargs = []
  479. f_objects = []
  480. if fmodule_sources:
  481. log.info("compiling Fortran 90 module sources")
  482. module_dirs = ext.module_dirs[:]
  483. module_build_dir = os.path.join(
  484. self.build_temp, os.path.dirname(
  485. self.get_ext_filename(fullname)))
  486. self.mkpath(module_build_dir)
  487. if fcompiler.module_dir_switch is None:
  488. existing_modules = glob('*.mod')
  489. extra_postargs += fcompiler.module_options(
  490. module_dirs, module_build_dir)
  491. f_objects += fcompiler.compile(fmodule_sources,
  492. output_dir=self.build_temp,
  493. macros=macros,
  494. include_dirs=include_dirs,
  495. debug=self.debug,
  496. extra_postargs=extra_postargs,
  497. depends=ext.depends)
  498. if fcompiler.module_dir_switch is None:
  499. for f in glob('*.mod'):
  500. if f in existing_modules:
  501. continue
  502. t = os.path.join(module_build_dir, f)
  503. if os.path.abspath(f) == os.path.abspath(t):
  504. continue
  505. if os.path.isfile(t):
  506. os.remove(t)
  507. try:
  508. self.move_file(f, module_build_dir)
  509. except DistutilsFileError:
  510. log.warn('failed to move %r to %r' %
  511. (f, module_build_dir))
  512. if f_sources:
  513. log.info("compiling Fortran sources")
  514. f_objects += fcompiler.compile(f_sources,
  515. output_dir=self.build_temp,
  516. macros=macros,
  517. include_dirs=include_dirs,
  518. debug=self.debug,
  519. extra_postargs=extra_postargs,
  520. depends=ext.depends)
  521. if f_objects and not fcompiler.can_ccompiler_link(self.compiler):
  522. unlinkable_fobjects = f_objects
  523. objects = c_objects
  524. else:
  525. unlinkable_fobjects = []
  526. objects = c_objects + f_objects
  527. if ext.extra_objects:
  528. objects.extend(ext.extra_objects)
  529. extra_args = ext.extra_link_args or []
  530. libraries = self.get_libraries(ext)[:]
  531. library_dirs = ext.library_dirs[:]
  532. linker = self.compiler.link_shared_object
  533. # Always use system linker when using MSVC compiler.
  534. if self.compiler.compiler_type in ('msvc', 'intelw', 'intelemw'):
  535. # expand libraries with fcompiler libraries as we are
  536. # not using fcompiler linker
  537. self._libs_with_msvc_and_fortran(
  538. fcompiler, libraries, library_dirs)
  539. if ext.runtime_library_dirs:
  540. # gcc adds RPATH to the link. On windows, copy the dll into
  541. # self.extra_dll_dir instead.
  542. for d in ext.runtime_library_dirs:
  543. for f in glob(d + '/*.dll'):
  544. copy_file(f, self.extra_dll_dir)
  545. ext.runtime_library_dirs = []
  546. elif ext.language in ['f77', 'f90'] and fcompiler is not None:
  547. linker = fcompiler.link_shared_object
  548. if ext.language == 'c++' and cxx_compiler is not None:
  549. linker = cxx_compiler.link_shared_object
  550. if fcompiler is not None:
  551. objects, libraries = self._process_unlinkable_fobjects(
  552. objects, libraries,
  553. fcompiler, library_dirs,
  554. unlinkable_fobjects)
  555. linker(objects, ext_filename,
  556. libraries=libraries,
  557. library_dirs=library_dirs,
  558. runtime_library_dirs=ext.runtime_library_dirs,
  559. extra_postargs=extra_args,
  560. export_symbols=self.get_export_symbols(ext),
  561. debug=self.debug,
  562. build_temp=self.build_temp,
  563. target_lang=ext.language)
  564. def _add_dummy_mingwex_sym(self, c_sources):
  565. build_src = self.get_finalized_command("build_src").build_src
  566. build_clib = self.get_finalized_command("build_clib").build_clib
  567. objects = self.compiler.compile([os.path.join(build_src,
  568. "gfortran_vs2003_hack.c")],
  569. output_dir=self.build_temp)
  570. self.compiler.create_static_lib(
  571. objects, "_gfortran_workaround", output_dir=build_clib, debug=self.debug)
  572. def _process_unlinkable_fobjects(self, objects, libraries,
  573. fcompiler, library_dirs,
  574. unlinkable_fobjects):
  575. libraries = list(libraries)
  576. objects = list(objects)
  577. unlinkable_fobjects = list(unlinkable_fobjects)
  578. # Expand possible fake static libraries to objects;
  579. # make sure to iterate over a copy of the list as
  580. # "fake" libraries will be removed as they are
  581. # encountered
  582. for lib in libraries[:]:
  583. for libdir in library_dirs:
  584. fake_lib = os.path.join(libdir, lib + '.fobjects')
  585. if os.path.isfile(fake_lib):
  586. # Replace fake static library
  587. libraries.remove(lib)
  588. with open(fake_lib) as f:
  589. unlinkable_fobjects.extend(f.read().splitlines())
  590. # Expand C objects
  591. c_lib = os.path.join(libdir, lib + '.cobjects')
  592. with open(c_lib) as f:
  593. objects.extend(f.read().splitlines())
  594. # Wrap unlinkable objects to a linkable one
  595. if unlinkable_fobjects:
  596. fobjects = [os.path.abspath(obj) for obj in unlinkable_fobjects]
  597. wrapped = fcompiler.wrap_unlinkable_objects(
  598. fobjects, output_dir=self.build_temp,
  599. extra_dll_dir=self.extra_dll_dir)
  600. objects.extend(wrapped)
  601. return objects, libraries
  602. def _libs_with_msvc_and_fortran(self, fcompiler, c_libraries,
  603. c_library_dirs):
  604. if fcompiler is None:
  605. return
  606. for libname in c_libraries:
  607. if libname.startswith('msvc'):
  608. continue
  609. fileexists = False
  610. for libdir in c_library_dirs or []:
  611. libfile = os.path.join(libdir, '%s.lib' % (libname))
  612. if os.path.isfile(libfile):
  613. fileexists = True
  614. break
  615. if fileexists:
  616. continue
  617. # make g77-compiled static libs available to MSVC
  618. fileexists = False
  619. for libdir in c_library_dirs:
  620. libfile = os.path.join(libdir, 'lib%s.a' % (libname))
  621. if os.path.isfile(libfile):
  622. # copy libname.a file to name.lib so that MSVC linker
  623. # can find it
  624. libfile2 = os.path.join(self.build_temp, libname + '.lib')
  625. copy_file(libfile, libfile2)
  626. if self.build_temp not in c_library_dirs:
  627. c_library_dirs.append(self.build_temp)
  628. fileexists = True
  629. break
  630. if fileexists:
  631. continue
  632. log.warn('could not find library %r in directories %s'
  633. % (libname, c_library_dirs))
  634. # Always use system linker when using MSVC compiler.
  635. f_lib_dirs = []
  636. for dir in fcompiler.library_dirs:
  637. # correct path when compiling in Cygwin but with normal Win
  638. # Python
  639. if dir.startswith('/usr/lib'):
  640. try:
  641. dir = subprocess.check_output(['cygpath', '-w', dir])
  642. except (OSError, subprocess.CalledProcessError):
  643. pass
  644. else:
  645. dir = filepath_from_subprocess_output(dir)
  646. f_lib_dirs.append(dir)
  647. c_library_dirs.extend(f_lib_dirs)
  648. # make g77-compiled static libs available to MSVC
  649. for lib in fcompiler.libraries:
  650. if not lib.startswith('msvc'):
  651. c_libraries.append(lib)
  652. p = combine_paths(f_lib_dirs, 'lib' + lib + '.a')
  653. if p:
  654. dst_name = os.path.join(self.build_temp, lib + '.lib')
  655. if not os.path.isfile(dst_name):
  656. copy_file(p[0], dst_name)
  657. if self.build_temp not in c_library_dirs:
  658. c_library_dirs.append(self.build_temp)
  659. def get_source_files(self):
  660. self.check_extensions_list(self.extensions)
  661. filenames = []
  662. for ext in self.extensions:
  663. filenames.extend(get_ext_source_files(ext))
  664. return filenames
  665. def get_outputs(self):
  666. self.check_extensions_list(self.extensions)
  667. outputs = []
  668. for ext in self.extensions:
  669. if not ext.sources:
  670. continue
  671. fullname = self.get_ext_fullname(ext.name)
  672. outputs.append(os.path.join(self.build_lib,
  673. self.get_ext_filename(fullname)))
  674. return outputs