PageRenderTime 56ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/distutils/ccompiler.py

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