ccompiler.py 48 KB

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