ccompiler.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  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 source 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. finally:
  681. os.remove(fname)
  682. try:
  683. self.link_executable(objects, "a.out",
  684. libraries=libraries,
  685. library_dirs=library_dirs)
  686. except (LinkError, TypeError):
  687. return False
  688. else:
  689. os.remove("a.out")
  690. finally:
  691. for fn in objects:
  692. os.remove(fn)
  693. return True
  694. def find_library_file (self, dirs, lib, debug=0):
  695. """Search the specified list of directories for a static or shared
  696. library file 'lib' and return the full path to that file. If
  697. 'debug' true, look for a debugging version (if that makes sense on
  698. the current platform). Return None if 'lib' wasn't found in any of
  699. the specified directories.
  700. """
  701. raise NotImplementedError
  702. # -- Filename generation methods -----------------------------------
  703. # The default implementation of the filename generating methods are
  704. # prejudiced towards the Unix/DOS/Windows view of the world:
  705. # * object files are named by replacing the source file extension
  706. # (eg. .c/.cpp -> .o/.obj)
  707. # * library files (shared or static) are named by plugging the
  708. # library name and extension into a format string, eg.
  709. # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
  710. # * executables are named by appending an extension (possibly
  711. # empty) to the program name: eg. progname + ".exe" for
  712. # Windows
  713. #
  714. # To reduce redundant code, these methods expect to find
  715. # several attributes in the current object (presumably defined
  716. # as class attributes):
  717. # * src_extensions -
  718. # list of C/C++ source file extensions, eg. ['.c', '.cpp']
  719. # * obj_extension -
  720. # object file extension, eg. '.o' or '.obj'
  721. # * static_lib_extension -
  722. # extension for static library files, eg. '.a' or '.lib'
  723. # * shared_lib_extension -
  724. # extension for shared library/object files, eg. '.so', '.dll'
  725. # * static_lib_format -
  726. # format string for generating static library filenames,
  727. # eg. 'lib%s.%s' or '%s.%s'
  728. # * shared_lib_format
  729. # format string for generating shared library filenames
  730. # (probably same as static_lib_format, since the extension
  731. # is one of the intended parameters to the format string)
  732. # * exe_extension -
  733. # extension for executable files, eg. '' or '.exe'
  734. def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
  735. if output_dir is None:
  736. output_dir = ''
  737. obj_names = []
  738. for src_name in source_filenames:
  739. base, ext = os.path.splitext(src_name)
  740. base = os.path.splitdrive(base)[1] # Chop off the drive
  741. base = base[os.path.isabs(base):] # If abs, chop off leading /
  742. if ext not in self.src_extensions:
  743. raise UnknownFileError(
  744. "unknown file type '%s' (from '%s')" % (ext, src_name))
  745. if strip_dir:
  746. base = os.path.basename(base)
  747. obj_names.append(os.path.join(output_dir,
  748. base + self.obj_extension))
  749. return obj_names
  750. def shared_object_filename(self, basename, strip_dir=0, output_dir=''):
  751. assert output_dir is not None
  752. if strip_dir:
  753. basename = os.path.basename(basename)
  754. return os.path.join(output_dir, basename + self.shared_lib_extension)
  755. def executable_filename(self, basename, strip_dir=0, output_dir=''):
  756. assert output_dir is not None
  757. if strip_dir:
  758. basename = os.path.basename(basename)
  759. return os.path.join(output_dir, basename + (self.exe_extension or ''))
  760. def library_filename(self, libname, lib_type='static', # or 'shared'
  761. strip_dir=0, output_dir=''):
  762. assert output_dir is not None
  763. if lib_type not in ("static", "shared", "dylib", "xcode_stub"):
  764. raise ValueError(
  765. "'lib_type' must be \"static\", \"shared\", \"dylib\", or \"xcode_stub\"")
  766. fmt = getattr(self, lib_type + "_lib_format")
  767. ext = getattr(self, lib_type + "_lib_extension")
  768. dir, base = os.path.split(libname)
  769. filename = fmt % (base, ext)
  770. if strip_dir:
  771. dir = ''
  772. return os.path.join(output_dir, dir, filename)
  773. # -- Utility methods -----------------------------------------------
  774. def announce(self, msg, level=1):
  775. log.debug(msg)
  776. def debug_print(self, msg):
  777. from distutils.debug import DEBUG
  778. if DEBUG:
  779. print(msg)
  780. def warn(self, msg):
  781. sys.stderr.write("warning: %s\n" % msg)
  782. def execute(self, func, args, msg=None, level=1):
  783. execute(func, args, msg, self.dry_run)
  784. def spawn(self, cmd, **kwargs):
  785. spawn(cmd, dry_run=self.dry_run, **kwargs)
  786. def move_file(self, src, dst):
  787. return move_file(src, dst, dry_run=self.dry_run)
  788. def mkpath (self, name, mode=0o777):
  789. mkpath(name, mode, dry_run=self.dry_run)
  790. # Map a sys.platform/os.name ('posix', 'nt') to the default compiler
  791. # type for that platform. Keys are interpreted as re match
  792. # patterns. Order is important; platform mappings are preferred over
  793. # OS names.
  794. _default_compilers = (
  795. # Platform string mappings
  796. # on a cygwin built python we can use gcc like an ordinary UNIXish
  797. # compiler
  798. ('cygwin.*', 'unix'),
  799. # OS name mappings
  800. ('posix', 'unix'),
  801. ('nt', 'msvc'),
  802. )
  803. def get_default_compiler(osname=None, platform=None):
  804. """Determine the default compiler to use for the given platform.
  805. osname should be one of the standard Python OS names (i.e. the
  806. ones returned by os.name) and platform the common value
  807. returned by sys.platform for the platform in question.
  808. The default values are os.name and sys.platform in case the
  809. parameters are not given.
  810. """
  811. if osname is None:
  812. osname = os.name
  813. if platform is None:
  814. platform = sys.platform
  815. for pattern, compiler in _default_compilers:
  816. if re.match(pattern, platform) is not None or \
  817. re.match(pattern, osname) is not None:
  818. return compiler
  819. # Default to Unix compiler
  820. return 'unix'
  821. # Map compiler types to (module_name, class_name) pairs -- ie. where to
  822. # find the code that implements an interface to this compiler. (The module
  823. # is assumed to be in the 'distutils' package.)
  824. compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler',
  825. "standard UNIX-style compiler"),
  826. 'msvc': ('_msvccompiler', 'MSVCCompiler',
  827. "Microsoft Visual C++"),
  828. 'cygwin': ('cygwinccompiler', 'CygwinCCompiler',
  829. "Cygwin port of GNU C Compiler for Win32"),
  830. 'mingw32': ('cygwinccompiler', 'Mingw32CCompiler',
  831. "Mingw32 port of GNU C Compiler for Win32"),
  832. 'bcpp': ('bcppcompiler', 'BCPPCompiler',
  833. "Borland C++ Compiler"),
  834. }
  835. def show_compilers():
  836. """Print list of available compilers (used by the "--help-compiler"
  837. options to "build", "build_ext", "build_clib").
  838. """
  839. # XXX this "knows" that the compiler option it's describing is
  840. # "--compiler", which just happens to be the case for the three
  841. # commands that use it.
  842. from distutils.fancy_getopt import FancyGetopt
  843. compilers = []
  844. for compiler in compiler_class.keys():
  845. compilers.append(("compiler="+compiler, None,
  846. compiler_class[compiler][2]))
  847. compilers.sort()
  848. pretty_printer = FancyGetopt(compilers)
  849. pretty_printer.print_help("List of available compilers:")
  850. def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):
  851. """Generate an instance of some CCompiler subclass for the supplied
  852. platform/compiler combination. 'plat' defaults to 'os.name'
  853. (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
  854. for that platform. Currently only 'posix' and 'nt' are supported, and
  855. the default compilers are "traditional Unix interface" (UnixCCompiler
  856. class) and Visual C++ (MSVCCompiler class). Note that it's perfectly
  857. possible to ask for a Unix compiler object under Windows, and a
  858. Microsoft compiler object under Unix -- if you supply a value for
  859. 'compiler', 'plat' is ignored.
  860. """
  861. if plat is None:
  862. plat = os.name
  863. try:
  864. if compiler is None:
  865. compiler = get_default_compiler(plat)
  866. (module_name, class_name, long_description) = compiler_class[compiler]
  867. except KeyError:
  868. msg = "don't know how to compile C/C++ code on platform '%s'" % plat
  869. if compiler is not None:
  870. msg = msg + " with '%s' compiler" % compiler
  871. raise DistutilsPlatformError(msg)
  872. try:
  873. module_name = "distutils." + module_name
  874. __import__ (module_name)
  875. module = sys.modules[module_name]
  876. klass = vars(module)[class_name]
  877. except ImportError:
  878. raise DistutilsModuleError(
  879. "can't compile C/C++ code: unable to load module '%s'" % \
  880. module_name)
  881. except KeyError:
  882. raise DistutilsModuleError(
  883. "can't compile C/C++ code: unable to find class '%s' "
  884. "in module '%s'" % (class_name, module_name))
  885. # XXX The None is necessary to preserve backwards compatibility
  886. # with classes that expect verbose to be the first positional
  887. # argument.
  888. return klass(None, dry_run, force)
  889. def gen_preprocess_options(macros, include_dirs):
  890. """Generate C pre-processor options (-D, -U, -I) as used by at least
  891. two types of compilers: the typical Unix compiler and Visual C++.
  892. 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
  893. means undefine (-U) macro 'name', and (name,value) means define (-D)
  894. macro 'name' to 'value'. 'include_dirs' is just a list of directory
  895. names to be added to the header file search path (-I). Returns a list
  896. of command-line options suitable for either Unix compilers or Visual
  897. C++.
  898. """
  899. # XXX it would be nice (mainly aesthetic, and so we don't generate
  900. # stupid-looking command lines) to go over 'macros' and eliminate
  901. # redundant definitions/undefinitions (ie. ensure that only the
  902. # latest mention of a particular macro winds up on the command
  903. # line). I don't think it's essential, though, since most (all?)
  904. # Unix C compilers only pay attention to the latest -D or -U
  905. # mention of a macro on their command line. Similar situation for
  906. # 'include_dirs'. I'm punting on both for now. Anyways, weeding out
  907. # redundancies like this should probably be the province of
  908. # CCompiler, since the data structures used are inherited from it
  909. # and therefore common to all CCompiler classes.
  910. pp_opts = []
  911. for macro in macros:
  912. if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):
  913. raise TypeError(
  914. "bad macro definition '%s': "
  915. "each element of 'macros' list must be a 1- or 2-tuple"
  916. % macro)
  917. if len(macro) == 1: # undefine this macro
  918. pp_opts.append("-U%s" % macro[0])
  919. elif len(macro) == 2:
  920. if macro[1] is None: # define with no explicit value
  921. pp_opts.append("-D%s" % macro[0])
  922. else:
  923. # XXX *don't* need to be clever about quoting the
  924. # macro value here, because we're going to avoid the
  925. # shell at all costs when we spawn the command!
  926. pp_opts.append("-D%s=%s" % macro)
  927. for dir in include_dirs:
  928. pp_opts.append("-I%s" % dir)
  929. return pp_opts
  930. def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
  931. """Generate linker options for searching library directories and
  932. linking with specific libraries. 'libraries' and 'library_dirs' are,
  933. respectively, lists of library names (not filenames!) and search
  934. directories. Returns a list of command-line options suitable for use
  935. with some compiler (depending on the two format strings passed in).
  936. """
  937. lib_opts = []
  938. for dir in library_dirs:
  939. lib_opts.append(compiler.library_dir_option(dir))
  940. for dir in runtime_library_dirs:
  941. opt = compiler.runtime_library_dir_option(dir)
  942. if isinstance(opt, list):
  943. lib_opts = lib_opts + opt
  944. else:
  945. lib_opts.append(opt)
  946. # XXX it's important that we *not* remove redundant library mentions!
  947. # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
  948. # resolve all symbols. I just hope we never have to say "-lfoo obj.o
  949. # -lbar" to get things to work -- that's certainly a possibility, but a
  950. # pretty nasty way to arrange your C code.
  951. for lib in libraries:
  952. (lib_dir, lib_name) = os.path.split(lib)
  953. if lib_dir:
  954. lib_file = compiler.find_library_file([lib_dir], lib_name)
  955. if lib_file:
  956. lib_opts.append(lib_file)
  957. else:
  958. compiler.warn("no library file corresponding to "
  959. "'%s' found (skipping)" % lib)
  960. else:
  961. lib_opts.append(compiler.library_option (lib))
  962. return lib_opts