ccompiler.py 46 KB

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