PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/distutils/ccompiler.py

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