base.py 53 KB

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