ccompiler.py 46 KB

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