PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

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

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