ccompiler.py 46 KB

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