PageRenderTime 30ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/distutils/ccompiler.py

http://github.com/IronLanguages/main
Python | 1096 lines | 957 code | 29 blank | 110 comment | 14 complexity | d46c6d848580593e43e07a6b5cd43b89 MD5 | raw file
Possible License(s): CPL-1.0, BSD-3-Clause, ISC, GPL-2.0, MPL-2.0-no-copyleft-exception
  1. """distutils.ccompiler
  2. Contains CCompiler, an abstract base class that defines the interface
  3. for the Distutils compiler abstraction model."""
  4. __revision__ = "$Id$"
  5. import sys
  6. import os
  7. import re
  8. from distutils.errors import (CompileError, LinkError, UnknownFileError,
  9. DistutilsPlatformError, DistutilsModuleError)
  10. from distutils.spawn import spawn
  11. from distutils.file_util import move_file
  12. from distutils.dir_util import mkpath
  13. from distutils.dep_util import newer_group
  14. from distutils.util import split_quoted, execute
  15. from distutils import log
  16. # following import is for backward compatibility
  17. from distutils.sysconfig import customize_compiler
  18. class CCompiler:
  19. """Abstract base class to define the interface that must be implemented
  20. by real compiler classes. Also has some utility methods used by
  21. several compiler classes.
  22. The basic idea behind a compiler abstraction class is that each
  23. instance can be used for all the compile/link steps in building a
  24. single project. Thus, attributes common to all of those compile and
  25. link steps -- include directories, macros to define, libraries to link
  26. against, etc. -- are attributes of the compiler instance. To allow for
  27. variability in how individual files are treated, most of those
  28. attributes may be varied on a per-compilation or per-link basis.
  29. """
  30. # 'compiler_type' is a class attribute that identifies this class. It
  31. # keeps code that wants to know what kind of compiler it's dealing with
  32. # from having to import all possible compiler classes just to do an
  33. # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type'
  34. # should really, really be one of the keys of the 'compiler_class'
  35. # dictionary (see below -- used by the 'new_compiler()' factory
  36. # function) -- authors of new compiler interface classes are
  37. # responsible for updating 'compiler_class'!
  38. compiler_type = None
  39. # XXX things not handled by this compiler abstraction model:
  40. # * client can't provide additional options for a compiler,
  41. # e.g. warning, optimization, debugging flags. Perhaps this
  42. # should be the domain of concrete compiler abstraction classes
  43. # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
  44. # class should have methods for the common ones.
  45. # * can't completely override the include or library searchg
  46. # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
  47. # I'm not sure how widely supported this is even by Unix
  48. # compilers, much less on other platforms. And I'm even less
  49. # sure how useful it is; maybe for cross-compiling, but
  50. # support for that is a ways off. (And anyways, cross
  51. # compilers probably have a dedicated binary with the
  52. # right paths compiled in. I hope.)
  53. # * can't do really freaky things with the library list/library
  54. # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
  55. # different versions of libfoo.a in different locations. I
  56. # think this is useless without the ability to null out the
  57. # library search path anyways.
  58. # Subclasses that rely on the standard filename generation methods
  59. # implemented below should override these; see the comment near
  60. # those methods ('object_filenames()' et. al.) for details:
  61. src_extensions = None # list of strings
  62. obj_extension = None # string
  63. static_lib_extension = None
  64. shared_lib_extension = None # string
  65. static_lib_format = None # format string
  66. shared_lib_format = None # prob. same as static_lib_format
  67. exe_extension = None # string
  68. # Default language settings. language_map is used to detect a source
  69. # file or Extension target language, checking source filenames.
  70. # language_order is used to detect the language precedence, when deciding
  71. # what language to use when mixing source types. For example, if some
  72. # extension has two files with ".c" extension, and one with ".cpp", it
  73. # is still linked as c++.
  74. language_map = {".c" : "c",
  75. ".cc" : "c++",
  76. ".cpp" : "c++",
  77. ".cxx" : "c++",
  78. ".m" : "objc",
  79. }
  80. language_order = ["c++", "objc", "c"]
  81. def __init__ (self, verbose=0, dry_run=0, force=0):
  82. self.dry_run = dry_run
  83. self.force = force
  84. self.verbose = verbose
  85. # 'output_dir': a common output directory for object, library,
  86. # shared object, and shared library files
  87. self.output_dir = None
  88. # 'macros': a list of macro definitions (or undefinitions). A
  89. # macro definition is a 2-tuple (name, value), where the value is
  90. # either a string or None (no explicit value). A macro
  91. # undefinition is a 1-tuple (name,).
  92. self.macros = []
  93. # 'include_dirs': a list of directories to search for include files
  94. self.include_dirs = []
  95. # 'libraries': a list of libraries to include in any link
  96. # (library names, not filenames: eg. "foo" not "libfoo.a")
  97. self.libraries = []
  98. # 'library_dirs': a list of directories to search for libraries
  99. self.library_dirs = []
  100. # 'runtime_library_dirs': a list of directories to search for
  101. # shared libraries/objects at runtime
  102. self.runtime_library_dirs = []
  103. # 'objects': a list of object files (or similar, such as explicitly
  104. # named library files) to include on any link
  105. self.objects = []
  106. for key in self.executables.keys():
  107. self.set_executable(key, self.executables[key])
  108. def set_executables(self, **args):
  109. """Define the executables (and options for them) that will be run
  110. to perform the various stages of compilation. The exact set of
  111. executables that may be specified here depends on the compiler
  112. class (via the 'executables' class attribute), but most will have:
  113. compiler the C/C++ compiler
  114. linker_so linker used to create shared objects and libraries
  115. linker_exe linker used to create binary executables
  116. archiver static library creator
  117. On platforms with a command-line (Unix, DOS/Windows), each of these
  118. is a string that will be split into executable name and (optional)
  119. list of arguments. (Splitting the string is done similarly to how
  120. Unix shells operate: words are delimited by spaces, but quotes and
  121. backslashes can override this. See
  122. 'distutils.util.split_quoted()'.)
  123. """
  124. # Note that some CCompiler implementation classes will define class
  125. # attributes 'cpp', 'cc', etc. with hard-coded executable names;
  126. # this is appropriate when a compiler class is for exactly one
  127. # compiler/OS combination (eg. MSVCCompiler). Other compiler
  128. # classes (UnixCCompiler, in particular) are driven by information
  129. # discovered at run-time, since there are many different ways to do
  130. # basically the same things with Unix C compilers.
  131. for key in args.keys():
  132. if key not in self.executables:
  133. raise ValueError, \
  134. "unknown executable '%s' for class %s" % \
  135. (key, self.__class__.__name__)
  136. self.set_executable(key, args[key])
  137. def set_executable(self, key, value):
  138. if isinstance(value, str):
  139. setattr(self, key, split_quoted(value))
  140. else:
  141. setattr(self, key, value)
  142. def _find_macro(self, name):
  143. i = 0
  144. for defn in self.macros:
  145. if defn[0] == name:
  146. return i
  147. i = i + 1
  148. return None
  149. def _check_macro_definitions(self, definitions):
  150. """Ensures that every element of 'definitions' is a valid macro
  151. definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do
  152. nothing if all definitions are OK, raise TypeError otherwise.
  153. """
  154. for defn in definitions:
  155. if not (isinstance(defn, tuple) and
  156. (len (defn) == 1 or
  157. (len (defn) == 2 and
  158. (isinstance(defn[1], str) or defn[1] is None))) and
  159. isinstance(defn[0], str)):
  160. raise TypeError, \
  161. ("invalid macro definition '%s': " % defn) + \
  162. "must be tuple (string,), (string, string), or " + \
  163. "(string, None)"
  164. # -- Bookkeeping methods -------------------------------------------
  165. def define_macro(self, name, value=None):
  166. """Define a preprocessor macro for all compilations driven by this
  167. compiler object. The optional parameter 'value' should be a
  168. string; if it is not supplied, then the macro will be defined
  169. without an explicit value and the exact outcome depends on the
  170. compiler used (XXX true? does ANSI say anything about this?)
  171. """
  172. # Delete from the list of macro definitions/undefinitions if
  173. # already there (so that this one will take precedence).
  174. i = self._find_macro (name)
  175. if i is not None:
  176. del self.macros[i]
  177. defn = (name, value)
  178. self.macros.append (defn)
  179. def undefine_macro(self, name):
  180. """Undefine a preprocessor macro for all compilations driven by
  181. this compiler object. If the same macro is defined by
  182. 'define_macro()' and undefined by 'undefine_macro()' the last call
  183. takes precedence (including multiple redefinitions or
  184. undefinitions). If the macro is redefined/undefined on a
  185. per-compilation basis (ie. in the call to 'compile()'), then that
  186. takes precedence.
  187. """
  188. # Delete from the list of macro definitions/undefinitions if
  189. # already there (so that this one will take precedence).
  190. i = self._find_macro (name)
  191. if i is not None:
  192. del self.macros[i]
  193. undefn = (name,)
  194. self.macros.append (undefn)
  195. def add_include_dir(self, dir):
  196. """Add 'dir' to the list of directories that will be searched for
  197. header files. The compiler is instructed to search directories in
  198. the order in which they are supplied by successive calls to
  199. 'add_include_dir()'.
  200. """
  201. self.include_dirs.append (dir)
  202. def set_include_dirs(self, dirs):
  203. """Set the list of directories that will be searched to 'dirs' (a
  204. list of strings). Overrides any preceding calls to
  205. 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
  206. to the list passed to 'set_include_dirs()'. This does not affect
  207. any list of standard include directories that the compiler may
  208. search by default.
  209. """
  210. self.include_dirs = dirs[:]
  211. def add_library(self, libname):
  212. """Add 'libname' to the list of libraries that will be included in
  213. all links driven by this compiler object. Note that 'libname'
  214. should *not* be the name of a file containing a library, but the
  215. name of the library itself: the actual filename will be inferred by
  216. the linker, the compiler, or the compiler class (depending on the
  217. platform).
  218. The linker will be instructed to link against libraries in the
  219. order they were supplied to 'add_library()' and/or
  220. 'set_libraries()'. It is perfectly valid to duplicate library
  221. names; the linker will be instructed to link against libraries as
  222. many times as they are mentioned.
  223. """
  224. self.libraries.append (libname)
  225. def set_libraries(self, libnames):
  226. """Set the list of libraries to be included in all links driven by
  227. this compiler object to 'libnames' (a list of strings). This does
  228. not affect any standard system libraries that the linker may
  229. include by default.
  230. """
  231. self.libraries = libnames[:]
  232. def add_library_dir(self, dir):
  233. """Add 'dir' to the list of directories that will be searched for
  234. libraries specified to 'add_library()' and 'set_libraries()'. The
  235. linker will be instructed to search for libraries in the order they
  236. are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
  237. """
  238. self.library_dirs.append(dir)
  239. def set_library_dirs(self, dirs):
  240. """Set the list of library search directories to 'dirs' (a list of
  241. strings). This does not affect any standard library search path
  242. that the linker may search by default.
  243. """
  244. self.library_dirs = dirs[:]
  245. def add_runtime_library_dir(self, dir):
  246. """Add 'dir' to the list of directories that will be searched for
  247. shared libraries at runtime.
  248. """
  249. self.runtime_library_dirs.append(dir)
  250. def set_runtime_library_dirs(self, dirs):
  251. """Set the list of directories to search for shared libraries at
  252. runtime to 'dirs' (a list of strings). This does not affect any
  253. standard search path that the runtime linker may search by
  254. default.
  255. """
  256. self.runtime_library_dirs = dirs[:]
  257. def add_link_object(self, object):
  258. """Add 'object' to the list of object files (or analogues, such as
  259. explicitly named library files or the output of "resource
  260. compilers") to be included in every link driven by this compiler
  261. object.
  262. """
  263. self.objects.append(object)
  264. def set_link_objects(self, objects):
  265. """Set the list of object files (or analogues) to be included in
  266. every link to 'objects'. This does not affect any standard object
  267. files that the linker may include by default (such as system
  268. libraries).
  269. """
  270. self.objects = objects[:]
  271. # -- Private utility methods --------------------------------------
  272. # (here for the convenience of subclasses)
  273. # Helper method to prep compiler in subclass compile() methods
  274. def _setup_compile(self, outdir, macros, incdirs, sources, depends,
  275. extra):
  276. """Process arguments and decide which source files to compile."""
  277. if outdir is None:
  278. outdir = self.output_dir
  279. elif not isinstance(outdir, str):
  280. raise TypeError, "'output_dir' must be a string or None"
  281. if macros is None:
  282. macros = self.macros
  283. elif isinstance(macros, list):
  284. macros = macros + (self.macros or [])
  285. else:
  286. raise TypeError, "'macros' (if supplied) must be a list of tuples"
  287. if incdirs is None:
  288. incdirs = self.include_dirs
  289. elif isinstance(incdirs, (list, tuple)):
  290. incdirs = list(incdirs) + (self.include_dirs or [])
  291. else:
  292. raise TypeError, \
  293. "'include_dirs' (if supplied) must be a list of strings"
  294. if extra is None:
  295. extra = []
  296. # Get the list of expected output (object) files
  297. objects = self.object_filenames(sources,
  298. strip_dir=0,
  299. output_dir=outdir)
  300. assert len(objects) == len(sources)
  301. pp_opts = gen_preprocess_options(macros, incdirs)
  302. build = {}
  303. for i in range(len(sources)):
  304. src = sources[i]
  305. obj = objects[i]
  306. ext = os.path.splitext(src)[1]
  307. self.mkpath(os.path.dirname(obj))
  308. build[obj] = (src, ext)
  309. return macros, objects, extra, pp_opts, build
  310. def _get_cc_args(self, pp_opts, debug, before):
  311. # works for unixccompiler, emxccompiler, cygwinccompiler
  312. cc_args = pp_opts + ['-c']
  313. if debug:
  314. cc_args[:0] = ['-g']
  315. if before:
  316. cc_args[:0] = before
  317. return cc_args
  318. def _fix_compile_args(self, output_dir, macros, include_dirs):
  319. """Typecheck and fix-up some of the arguments to the 'compile()'
  320. method, and return fixed-up values. Specifically: if 'output_dir'
  321. is None, replaces it with 'self.output_dir'; ensures that 'macros'
  322. is a list, and augments it with 'self.macros'; ensures that
  323. 'include_dirs' is a list, and augments it with 'self.include_dirs'.
  324. Guarantees that the returned values are of the correct type,
  325. i.e. for 'output_dir' either string or None, and for 'macros' and
  326. 'include_dirs' either list or None.
  327. """
  328. if output_dir is None:
  329. output_dir = self.output_dir
  330. elif not isinstance(output_dir, str):
  331. raise TypeError, "'output_dir' must be a string or None"
  332. if macros is None:
  333. macros = self.macros
  334. elif isinstance(macros, list):
  335. macros = macros + (self.macros or [])
  336. else:
  337. raise TypeError, "'macros' (if supplied) must be a list of tuples"
  338. if include_dirs is None:
  339. include_dirs = self.include_dirs
  340. elif isinstance(include_dirs, (list, tuple)):
  341. include_dirs = list (include_dirs) + (self.include_dirs or [])
  342. else:
  343. raise TypeError, \
  344. "'include_dirs' (if supplied) must be a list of strings"
  345. return output_dir, macros, include_dirs
  346. def _fix_object_args(self, objects, output_dir):
  347. """Typecheck and fix up some arguments supplied to various methods.
  348. Specifically: ensure that 'objects' is a list; if output_dir is
  349. None, replace with self.output_dir. Return fixed versions of
  350. 'objects' and 'output_dir'.
  351. """
  352. if not isinstance(objects, (list, tuple)):
  353. raise TypeError, \
  354. "'objects' must be a list or tuple of strings"
  355. objects = list (objects)
  356. if output_dir is None:
  357. output_dir = self.output_dir
  358. elif not isinstance(output_dir, str):
  359. raise TypeError, "'output_dir' must be a string or None"
  360. return (objects, output_dir)
  361. def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
  362. """Typecheck and fix up some of the arguments supplied to the
  363. 'link_*' methods. Specifically: ensure that all arguments are
  364. lists, and augment them with their permanent versions
  365. (eg. 'self.libraries' augments 'libraries'). Return a tuple with
  366. fixed versions of all arguments.
  367. """
  368. if libraries is None:
  369. libraries = self.libraries
  370. elif isinstance(libraries, (list, tuple)):
  371. libraries = list (libraries) + (self.libraries or [])
  372. else:
  373. raise TypeError, \
  374. "'libraries' (if supplied) must be a list of strings"
  375. if library_dirs is None:
  376. library_dirs = self.library_dirs
  377. elif isinstance(library_dirs, (list, tuple)):
  378. library_dirs = list (library_dirs) + (self.library_dirs or [])
  379. else:
  380. raise TypeError, \
  381. "'library_dirs' (if supplied) must be a list of strings"
  382. if runtime_library_dirs is None:
  383. runtime_library_dirs = self.runtime_library_dirs
  384. elif isinstance(runtime_library_dirs, (list, tuple)):
  385. runtime_library_dirs = (list (runtime_library_dirs) +
  386. (self.runtime_library_dirs or []))
  387. else:
  388. raise TypeError, \
  389. "'runtime_library_dirs' (if supplied) " + \
  390. "must be a list of strings"
  391. return (libraries, library_dirs, runtime_library_dirs)
  392. def _need_link(self, objects, output_file):
  393. """Return true if we need to relink the files listed in 'objects'
  394. to recreate 'output_file'.
  395. """
  396. if self.force:
  397. return 1
  398. else:
  399. if self.dry_run:
  400. newer = newer_group (objects, output_file, missing='newer')
  401. else:
  402. newer = newer_group (objects, output_file)
  403. return newer
  404. def detect_language(self, sources):
  405. """Detect the language of a given file, or list of files. Uses
  406. language_map, and language_order to do the job.
  407. """
  408. if not isinstance(sources, list):
  409. sources = [sources]
  410. lang = None
  411. index = len(self.language_order)
  412. for source in sources:
  413. base, ext = os.path.splitext(source)
  414. extlang = self.language_map.get(ext)
  415. try:
  416. extindex = self.language_order.index(extlang)
  417. if extindex < index:
  418. lang = extlang
  419. index = extindex
  420. except ValueError:
  421. pass
  422. return lang
  423. # -- Worker methods ------------------------------------------------
  424. # (must be implemented by subclasses)
  425. def preprocess(self, source, output_file=None, macros=None,
  426. include_dirs=None, extra_preargs=None, extra_postargs=None):
  427. """Preprocess a single C/C++ source file, named in 'source'.
  428. Output will be written to file named 'output_file', or stdout if
  429. 'output_file' not supplied. 'macros' is a list of macro
  430. definitions as for 'compile()', which will augment the macros set
  431. with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a
  432. list of directory names that will be added to the default list.
  433. Raises PreprocessError on failure.
  434. """
  435. pass
  436. def compile(self, sources, output_dir=None, macros=None,
  437. include_dirs=None, debug=0, extra_preargs=None,
  438. extra_postargs=None, depends=None):
  439. """Compile one or more source files.
  440. 'sources' must be a list of filenames, most likely C/C++
  441. files, but in reality anything that can be handled by a
  442. particular compiler and compiler class (eg. MSVCCompiler can
  443. handle resource files in 'sources'). Return a list of object
  444. filenames, one per source filename in 'sources'. Depending on
  445. the implementation, not all source files will necessarily be
  446. compiled, but all corresponding object filenames will be
  447. returned.
  448. If 'output_dir' is given, object files will be put under it, while
  449. retaining their original path component. That is, "foo/bar.c"
  450. normally compiles to "foo/bar.o" (for a Unix implementation); if
  451. 'output_dir' is "build", then it would compile to
  452. "build/foo/bar.o".
  453. 'macros', if given, must be a list of macro definitions. A macro
  454. definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
  455. The former defines a macro; if the value is None, the macro is
  456. defined without an explicit value. The 1-tuple case undefines a
  457. macro. Later definitions/redefinitions/ undefinitions take
  458. precedence.
  459. 'include_dirs', if given, must be a list of strings, the
  460. directories to add to the default include file search path for this
  461. compilation only.
  462. 'debug' is a boolean; if true, the compiler will be instructed to
  463. output debug symbols in (or alongside) the object file(s).
  464. 'extra_preargs' and 'extra_postargs' are implementation- dependent.
  465. On platforms that have the notion of a command-line (e.g. Unix,
  466. DOS/Windows), they are most likely lists of strings: extra
  467. command-line arguments to prepand/append to the compiler command
  468. line. On other platforms, consult the implementation class
  469. documentation. In any event, they are intended as an escape hatch
  470. for those occasions when the abstract compiler framework doesn't
  471. cut the mustard.
  472. 'depends', if given, is a list of filenames that all targets
  473. depend on. If a source file is older than any file in
  474. depends, then the source file will be recompiled. This
  475. supports dependency tracking, but only at a coarse
  476. granularity.
  477. Raises CompileError on failure.
  478. """
  479. # A concrete compiler class can either override this method
  480. # entirely or implement _compile().
  481. macros, objects, extra_postargs, pp_opts, build = \
  482. self._setup_compile(output_dir, macros, include_dirs, sources,
  483. depends, extra_postargs)
  484. cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
  485. for obj in objects:
  486. try:
  487. src, ext = build[obj]
  488. except KeyError:
  489. continue
  490. self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
  491. # Return *all* object filenames, not just the ones we just built.
  492. return objects
  493. def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
  494. """Compile 'src' to product 'obj'."""
  495. # A concrete compiler class that does not override compile()
  496. # should implement _compile().
  497. pass
  498. def create_static_lib(self, objects, output_libname, output_dir=None,
  499. debug=0, target_lang=None):
  500. """Link a bunch of stuff together to create a static library file.
  501. The "bunch of stuff" consists of the list of object files supplied
  502. as 'objects', the extra object files supplied to
  503. 'add_link_object()' and/or 'set_link_objects()', the libraries
  504. supplied to 'add_library()' and/or 'set_libraries()', and the
  505. libraries supplied as 'libraries' (if any).
  506. 'output_libname' should be a library name, not a filename; the
  507. filename will be inferred from the library name. 'output_dir' is
  508. the directory where the library file will be put.
  509. 'debug' is a boolean; if true, debugging information will be
  510. included in the library (note that on most platforms, it is the
  511. compile step where this matters: the 'debug' flag is included here
  512. just for consistency).
  513. 'target_lang' is the target language for which the given objects
  514. are being compiled. This allows specific linkage time treatment of
  515. certain languages.
  516. Raises LibError on failure.
  517. """
  518. pass
  519. # values for target_desc parameter in link()
  520. SHARED_OBJECT = "shared_object"
  521. SHARED_LIBRARY = "shared_library"
  522. EXECUTABLE = "executable"
  523. def link(self, target_desc, objects, output_filename, output_dir=None,
  524. libraries=None, library_dirs=None, runtime_library_dirs=None,
  525. export_symbols=None, debug=0, extra_preargs=None,
  526. extra_postargs=None, build_temp=None, target_lang=None):
  527. """Link a bunch of stuff together to create an executable or
  528. shared library file.
  529. The "bunch of stuff" consists of the list of object files supplied
  530. as 'objects'. 'output_filename' should be a filename. If
  531. 'output_dir' is supplied, 'output_filename' is relative to it
  532. (i.e. 'output_filename' can provide directory components if
  533. needed).
  534. 'libraries' is a list of libraries to link against. These are
  535. library names, not filenames, since they're translated into
  536. filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
  537. on Unix and "foo.lib" on DOS/Windows). However, they can include a
  538. directory component, which means the linker will look in that
  539. specific directory rather than searching all the normal locations.
  540. 'library_dirs', if supplied, should be a list of directories to
  541. search for libraries that were specified as bare library names
  542. (ie. no directory component). These are on top of the system
  543. default and those supplied to 'add_library_dir()' and/or
  544. 'set_library_dirs()'. 'runtime_library_dirs' is a list of
  545. directories that will be embedded into the shared library and used
  546. to search for other shared libraries that *it* depends on at
  547. run-time. (This may only be relevant on Unix.)
  548. 'export_symbols' is a list of symbols that the shared library will
  549. export. (This appears to be relevant only on Windows.)
  550. 'debug' is as for 'compile()' and 'create_static_lib()', with the
  551. slight distinction that it actually matters on most platforms (as
  552. opposed to 'create_static_lib()', which includes a 'debug' flag
  553. mostly for form's sake).
  554. 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
  555. of course that they supply command-line arguments for the
  556. particular linker being used).
  557. 'target_lang' is the target language for which the given objects
  558. are being compiled. This allows specific linkage time treatment of
  559. certain languages.
  560. Raises LinkError on failure.
  561. """
  562. raise NotImplementedError
  563. # Old 'link_*()' methods, rewritten to use the new 'link()' method.
  564. def link_shared_lib(self, objects, output_libname, output_dir=None,
  565. libraries=None, library_dirs=None,
  566. runtime_library_dirs=None, export_symbols=None,
  567. debug=0, extra_preargs=None, extra_postargs=None,
  568. build_temp=None, target_lang=None):
  569. self.link(CCompiler.SHARED_LIBRARY, objects,
  570. self.library_filename(output_libname, lib_type='shared'),
  571. output_dir,
  572. libraries, library_dirs, runtime_library_dirs,
  573. export_symbols, debug,
  574. extra_preargs, extra_postargs, build_temp, target_lang)
  575. def link_shared_object(self, objects, output_filename, output_dir=None,
  576. libraries=None, library_dirs=None,
  577. runtime_library_dirs=None, export_symbols=None,
  578. debug=0, extra_preargs=None, extra_postargs=None,
  579. build_temp=None, target_lang=None):
  580. self.link(CCompiler.SHARED_OBJECT, objects,
  581. output_filename, output_dir,
  582. libraries, library_dirs, runtime_library_dirs,
  583. export_symbols, debug,
  584. extra_preargs, extra_postargs, build_temp, target_lang)
  585. def link_executable(self, objects, output_progname, output_dir=None,
  586. libraries=None, library_dirs=None,
  587. runtime_library_dirs=None, debug=0, extra_preargs=None,
  588. extra_postargs=None, target_lang=None):
  589. self.link(CCompiler.EXECUTABLE, objects,
  590. self.executable_filename(output_progname), output_dir,
  591. libraries, library_dirs, runtime_library_dirs, None,
  592. debug, extra_preargs, extra_postargs, None, target_lang)
  593. # -- Miscellaneous methods -----------------------------------------
  594. # These are all used by the 'gen_lib_options() function; there is
  595. # no appropriate default implementation so subclasses should
  596. # implement all of these.
  597. def library_dir_option(self, dir):
  598. """Return the compiler option to add 'dir' to the list of
  599. directories searched for libraries.
  600. """
  601. raise NotImplementedError
  602. def runtime_library_dir_option(self, dir):
  603. """Return the compiler option to add 'dir' to the list of
  604. directories searched for runtime libraries.
  605. """
  606. raise NotImplementedError
  607. def library_option(self, lib):
  608. """Return the compiler option to add 'lib' to the list of libraries
  609. linked into the shared library or executable.
  610. """
  611. raise NotImplementedError
  612. def has_function(self, funcname, includes=None, include_dirs=None,
  613. libraries=None, library_dirs=None):
  614. """Return a boolean indicating whether funcname is supported on
  615. the current platform. The optional arguments can be used to
  616. augment the compilation environment.
  617. """
  618. # this can't be included at module scope because it tries to
  619. # import math which might not be available at that point - maybe
  620. # the necessary logic should just be inlined?
  621. import tempfile
  622. if includes is None:
  623. includes = []
  624. if include_dirs is None:
  625. include_dirs = []
  626. if libraries is None:
  627. libraries = []
  628. if library_dirs is None:
  629. library_dirs = []
  630. fd, fname = tempfile.mkstemp(".c", funcname, text=True)
  631. f = os.fdopen(fd, "w")
  632. try:
  633. for incl in includes:
  634. f.write("""#include "%s"\n""" % incl)
  635. f.write("""\
  636. main (int argc, char **argv) {
  637. %s();
  638. }
  639. """ % funcname)
  640. finally:
  641. f.close()
  642. try:
  643. objects = self.compile([fname], include_dirs=include_dirs)
  644. except CompileError:
  645. return False
  646. try:
  647. self.link_executable(objects, "a.out",
  648. libraries=libraries,
  649. library_dirs=library_dirs)
  650. except (LinkError, TypeError):
  651. return False
  652. return True
  653. def find_library_file (self, dirs, lib, debug=0):
  654. """Search the specified list of directories for a static or shared
  655. library file 'lib' and return the full path to that file. If
  656. 'debug' true, look for a debugging version (if that makes sense on
  657. the current platform). Return None if 'lib' wasn't found in any of
  658. the specified directories.
  659. """
  660. raise NotImplementedError
  661. # -- Filename generation methods -----------------------------------
  662. # The default implementation of the filename generating methods are
  663. # prejudiced towards the Unix/DOS/Windows view of the world:
  664. # * object files are named by replacing the source file extension
  665. # (eg. .c/.cpp -> .o/.obj)
  666. # * library files (shared or static) are named by plugging the
  667. # library name and extension into a format string, eg.
  668. # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
  669. # * executables are named by appending an extension (possibly
  670. # empty) to the program name: eg. progname + ".exe" for
  671. # Windows
  672. #
  673. # To reduce redundant code, these methods expect to find
  674. # several attributes in the current object (presumably defined
  675. # as class attributes):
  676. # * src_extensions -
  677. # list of C/C++ source file extensions, eg. ['.c', '.cpp']
  678. # * obj_extension -
  679. # object file extension, eg. '.o' or '.obj'
  680. # * static_lib_extension -
  681. # extension for static library files, eg. '.a' or '.lib'
  682. # * shared_lib_extension -
  683. # extension for shared library/object files, eg. '.so', '.dll'
  684. # * static_lib_format -
  685. # format string for generating static library filenames,
  686. # eg. 'lib%s.%s' or '%s.%s'
  687. # * shared_lib_format
  688. # format string for generating shared library filenames
  689. # (probably same as static_lib_format, since the extension
  690. # is one of the intended parameters to the format string)
  691. # * exe_extension -
  692. # extension for executable files, eg. '' or '.exe'
  693. def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
  694. if output_dir is None:
  695. output_dir = ''
  696. obj_names = []
  697. for src_name in source_filenames:
  698. base, ext = os.path.splitext(src_name)
  699. base = os.path.splitdrive(base)[1] # Chop off the drive
  700. base = base[os.path.isabs(base):] # If abs, chop off leading /
  701. if ext not in self.src_extensions:
  702. raise UnknownFileError, \
  703. "unknown file type '%s' (from '%s')" % (ext, src_name)
  704. if strip_dir:
  705. base = os.path.basename(base)
  706. obj_names.append(os.path.join(output_dir,
  707. base + self.obj_extension))
  708. return obj_names
  709. def shared_object_filename(self, basename, strip_dir=0, output_dir=''):
  710. assert output_dir is not None
  711. if strip_dir:
  712. basename = os.path.basename (basename)
  713. return os.path.join(output_dir, basename + self.shared_lib_extension)
  714. def executable_filename(self, basename, strip_dir=0, output_dir=''):
  715. assert output_dir is not None
  716. if strip_dir:
  717. basename = os.path.basename (basename)
  718. return os.path.join(output_dir, basename + (self.exe_extension or ''))
  719. def library_filename(self, libname, lib_type='static', # or 'shared'
  720. strip_dir=0, output_dir=''):
  721. assert output_dir is not None
  722. if lib_type not in ("static", "shared", "dylib", "xcode_stub"):
  723. raise ValueError, ("""'lib_type' must be "static", "shared", """
  724. """"dylib", or "xcode_stub".""")
  725. fmt = getattr(self, lib_type + "_lib_format")
  726. ext = getattr(self, lib_type + "_lib_extension")
  727. dir, base = os.path.split (libname)
  728. filename = fmt % (base, ext)
  729. if strip_dir:
  730. dir = ''
  731. return os.path.join(output_dir, dir, filename)
  732. # -- Utility methods -----------------------------------------------
  733. def announce(self, msg, level=1):
  734. log.debug(msg)
  735. def debug_print(self, msg):
  736. from distutils.debug import DEBUG
  737. if DEBUG:
  738. print msg
  739. def warn(self, msg):
  740. sys.stderr.write("warning: %s\n" % msg)
  741. def execute(self, func, args, msg=None, level=1):
  742. execute(func, args, msg, self.dry_run)
  743. def spawn(self, cmd):
  744. spawn(cmd, dry_run=self.dry_run)
  745. def move_file(self, src, dst):
  746. return move_file(src, dst, dry_run=self.dry_run)
  747. def mkpath(self, name, mode=0777):
  748. mkpath(name, mode, dry_run=self.dry_run)
  749. # class CCompiler
  750. # Map a sys.platform/os.name ('posix', 'nt') to the default compiler
  751. # type for that platform. Keys are interpreted as re match
  752. # patterns. Order is important; platform mappings are preferred over
  753. # OS names.
  754. _default_compilers = (
  755. # Platform string mappings
  756. # on a cygwin built python we can use gcc like an ordinary UNIXish
  757. # compiler
  758. ('cygwin.*', 'unix'),
  759. ('os2emx', 'emx'),
  760. # OS name mappings
  761. ('posix', 'unix'),
  762. ('nt', 'msvc'),
  763. )
  764. def get_default_compiler(osname=None, platform=None):
  765. """ Determine the default compiler to use for the given platform.
  766. osname should be one of the standard Python OS names (i.e. the
  767. ones returned by os.name) and platform the common value
  768. returned by sys.platform for the platform in question.
  769. The default values are os.name and sys.platform in case the
  770. parameters are not given.
  771. """
  772. if osname is None:
  773. osname = os.name
  774. if platform is None:
  775. platform = sys.platform
  776. for pattern, compiler in _default_compilers:
  777. if re.match(pattern, platform) is not None or \
  778. re.match(pattern, osname) is not None:
  779. return compiler
  780. # Default to Unix compiler
  781. return 'unix'
  782. # Map compiler types to (module_name, class_name) pairs -- ie. where to
  783. # find the code that implements an interface to this compiler. (The module
  784. # is assumed to be in the 'distutils' package.)
  785. compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler',
  786. "standard UNIX-style compiler"),
  787. 'msvc': ('msvccompiler', 'MSVCCompiler',
  788. "Microsoft Visual C++"),
  789. 'cygwin': ('cygwinccompiler', 'CygwinCCompiler',
  790. "Cygwin port of GNU C Compiler for Win32"),
  791. 'mingw32': ('cygwinccompiler', 'Mingw32CCompiler',
  792. "Mingw32 port of GNU C Compiler for Win32"),
  793. 'bcpp': ('bcppcompiler', 'BCPPCompiler',
  794. "Borland C++ Compiler"),
  795. 'emx': ('emxccompiler', 'EMXCCompiler',
  796. "EMX port of GNU C Compiler for OS/2"),
  797. }
  798. def show_compilers():
  799. """Print list of available compilers (used by the "--help-compiler"
  800. options to "build", "build_ext", "build_clib").
  801. """
  802. # XXX this "knows" that the compiler option it's describing is
  803. # "--compiler", which just happens to be the case for the three
  804. # commands that use it.
  805. from distutils.fancy_getopt import FancyGetopt
  806. compilers = []
  807. for compiler in compiler_class.keys():
  808. compilers.append(("compiler="+compiler, None,
  809. compiler_class[compiler][2]))
  810. compilers.sort()
  811. pretty_printer = FancyGetopt(compilers)
  812. pretty_printer.print_help("List of available compilers:")
  813. def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):
  814. """Generate an instance of some CCompiler subclass for the supplied
  815. platform/compiler combination. 'plat' defaults to 'os.name'
  816. (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
  817. for that platform. Currently only 'posix' and 'nt' are supported, and
  818. the default compilers are "traditional Unix interface" (UnixCCompiler
  819. class) and Visual C++ (MSVCCompiler class). Note that it's perfectly
  820. possible to ask for a Unix compiler object under Windows, and a
  821. Microsoft compiler object under Unix -- if you supply a value for
  822. 'compiler', 'plat' is ignored.
  823. """
  824. if plat is None:
  825. plat = os.name
  826. try:
  827. if compiler is None:
  828. compiler = get_default_compiler(plat)
  829. (module_name, class_name, long_description) = compiler_class[compiler]
  830. except KeyError:
  831. msg = "don't know how to compile C/C++ code on platform '%s'" % plat
  832. if compiler is not None:
  833. msg = msg + " with '%s' compiler" % compiler
  834. raise DistutilsPlatformError, msg
  835. try:
  836. module_name = "distutils." + module_name
  837. __import__ (module_name)
  838. module = sys.modules[module_name]
  839. klass = vars(module)[class_name]
  840. except ImportError:
  841. raise DistutilsModuleError, \
  842. "can't compile C/C++ code: unable to load module '%s'" % \
  843. module_name
  844. except KeyError:
  845. raise DistutilsModuleError, \
  846. ("can't compile C/C++ code: unable to find class '%s' " +
  847. "in module '%s'") % (class_name, module_name)
  848. # XXX The None is necessary to preserve backwards compatibility
  849. # with classes that expect verbose to be the first positional
  850. # argument.
  851. return klass(None, dry_run, force)
  852. def gen_preprocess_options(macros, include_dirs):
  853. """Generate C pre-processor options (-D, -U, -I) as used by at least
  854. two types of compilers: the typical Unix compiler and Visual C++.
  855. 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
  856. means undefine (-U) macro 'name', and (name,value) means define (-D)
  857. macro 'name' to 'value'. 'include_dirs' is just a list of directory
  858. names to be added to the header file search path (-I). Returns a list
  859. of command-line options suitable for either Unix compilers or Visual
  860. C++.
  861. """
  862. # XXX it would be nice (mainly aesthetic, and so we don't generate
  863. # stupid-looking command lines) to go over 'macros' and eliminate
  864. # redundant definitions/undefinitions (ie. ensure that only the
  865. # latest mention of a particular macro winds up on the command
  866. # line). I don't think it's essential, though, since most (all?)
  867. # Unix C compilers only pay attention to the latest -D or -U
  868. # mention of a macro on their command line. Similar situation for
  869. # 'include_dirs'. I'm punting on both for now. Anyways, weeding out
  870. # redundancies like this should probably be the province of
  871. # CCompiler, since the data structures used are inherited from it
  872. # and therefore common to all CCompiler classes.
  873. pp_opts = []
  874. for macro in macros:
  875. if not (isinstance(macro, tuple) and
  876. 1 <= len (macro) <= 2):
  877. raise TypeError, \
  878. ("bad macro definition '%s': " +
  879. "each element of 'macros' list must be a 1- or 2-tuple") % \
  880. macro
  881. if len (macro) == 1: # undefine this macro
  882. pp_opts.append ("-U%s" % macro[0])
  883. elif len (macro) == 2:
  884. if macro[1] is None: # define with no explicit value
  885. pp_opts.append ("-D%s" % macro[0])
  886. else:
  887. # XXX *don't* need to be clever about quoting the
  888. # macro value here, because we're going to avoid the
  889. # shell at all costs when we spawn the command!
  890. pp_opts.append ("-D%s=%s" % macro)
  891. for dir in include_dirs:
  892. pp_opts.append ("-I%s" % dir)
  893. return pp_opts
  894. def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):
  895. """Generate linker options for searching library directories and
  896. linking with specific libraries.
  897. 'libraries' and 'library_dirs' are, respectively, lists of library names
  898. (not filenames!) and search directories. Returns a list of command-line
  899. options suitable for use with some compiler (depending on the two format
  900. strings passed in).
  901. """
  902. lib_opts = []
  903. for dir in library_dirs:
  904. lib_opts.append(compiler.library_dir_option(dir))
  905. for dir in runtime_library_dirs:
  906. opt = compiler.runtime_library_dir_option(dir)
  907. if isinstance(opt, list):
  908. lib_opts.extend(opt)
  909. else:
  910. lib_opts.append(opt)
  911. # XXX it's important that we *not* remove redundant library mentions!
  912. # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
  913. # resolve all symbols. I just hope we never have to say "-lfoo obj.o
  914. # -lbar" to get things to work -- that's certainly a possibility, but a
  915. # pretty nasty way to arrange your C code.
  916. for lib in libraries:
  917. lib_dir, lib_name = os.path.split(lib)
  918. if lib_dir != '':
  919. lib_file = compiler.find_library_file([lib_dir], lib_name)
  920. if lib_file is not None:
  921. lib_opts.append(lib_file)
  922. else:
  923. compiler.warn("no library file corresponding to "
  924. "'%s' found (skipping)" % lib)
  925. else:
  926. lib_opts.append(compiler.library_option(lib))
  927. return lib_opts