Path: blob/main/test/lib/python3.9/site-packages/setuptools/_distutils/ccompiler.py
4799 views
"""distutils.ccompiler12Contains CCompiler, an abstract base class that defines the interface3for the Distutils compiler abstraction model."""45import sys, os, re6from distutils.errors import *7from distutils.spawn import spawn8from distutils.file_util import move_file9from distutils.dir_util import mkpath10from distutils.dep_util import newer_group11from distutils.util import split_quoted, execute12from distutils import log1314class CCompiler:15"""Abstract base class to define the interface that must be implemented16by real compiler classes. Also has some utility methods used by17several compiler classes.1819The basic idea behind a compiler abstraction class is that each20instance can be used for all the compile/link steps in building a21single project. Thus, attributes common to all of those compile and22link steps -- include directories, macros to define, libraries to link23against, etc. -- are attributes of the compiler instance. To allow for24variability in how individual files are treated, most of those25attributes may be varied on a per-compilation or per-link basis.26"""2728# 'compiler_type' is a class attribute that identifies this class. It29# keeps code that wants to know what kind of compiler it's dealing with30# from having to import all possible compiler classes just to do an31# 'isinstance'. In concrete CCompiler subclasses, 'compiler_type'32# should really, really be one of the keys of the 'compiler_class'33# dictionary (see below -- used by the 'new_compiler()' factory34# function) -- authors of new compiler interface classes are35# responsible for updating 'compiler_class'!36compiler_type = None3738# XXX things not handled by this compiler abstraction model:39# * client can't provide additional options for a compiler,40# e.g. warning, optimization, debugging flags. Perhaps this41# should be the domain of concrete compiler abstraction classes42# (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base43# class should have methods for the common ones.44# * can't completely override the include or library searchg45# path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".46# I'm not sure how widely supported this is even by Unix47# compilers, much less on other platforms. And I'm even less48# sure how useful it is; maybe for cross-compiling, but49# support for that is a ways off. (And anyways, cross50# compilers probably have a dedicated binary with the51# right paths compiled in. I hope.)52# * can't do really freaky things with the library list/library53# dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against54# different versions of libfoo.a in different locations. I55# think this is useless without the ability to null out the56# library search path anyways.575859# Subclasses that rely on the standard filename generation methods60# implemented below should override these; see the comment near61# those methods ('object_filenames()' et. al.) for details:62src_extensions = None # list of strings63obj_extension = None # string64static_lib_extension = None65shared_lib_extension = None # string66static_lib_format = None # format string67shared_lib_format = None # prob. same as static_lib_format68exe_extension = None # string6970# Default language settings. language_map is used to detect a source71# file or Extension target language, checking source filenames.72# language_order is used to detect the language precedence, when deciding73# what language to use when mixing source types. For example, if some74# extension has two files with ".c" extension, and one with ".cpp", it75# is still linked as c++.76language_map = {".c" : "c",77".cc" : "c++",78".cpp" : "c++",79".cxx" : "c++",80".m" : "objc",81}82language_order = ["c++", "objc", "c"]8384def __init__(self, verbose=0, dry_run=0, force=0):85self.dry_run = dry_run86self.force = force87self.verbose = verbose8889# 'output_dir': a common output directory for object, library,90# shared object, and shared library files91self.output_dir = None9293# 'macros': a list of macro definitions (or undefinitions). A94# macro definition is a 2-tuple (name, value), where the value is95# either a string or None (no explicit value). A macro96# undefinition is a 1-tuple (name,).97self.macros = []9899# 'include_dirs': a list of directories to search for include files100self.include_dirs = []101102# 'libraries': a list of libraries to include in any link103# (library names, not filenames: eg. "foo" not "libfoo.a")104self.libraries = []105106# 'library_dirs': a list of directories to search for libraries107self.library_dirs = []108109# 'runtime_library_dirs': a list of directories to search for110# shared libraries/objects at runtime111self.runtime_library_dirs = []112113# 'objects': a list of object files (or similar, such as explicitly114# named library files) to include on any link115self.objects = []116117for key in self.executables.keys():118self.set_executable(key, self.executables[key])119120def set_executables(self, **kwargs):121"""Define the executables (and options for them) that will be run122to perform the various stages of compilation. The exact set of123executables that may be specified here depends on the compiler124class (via the 'executables' class attribute), but most will have:125compiler the C/C++ compiler126linker_so linker used to create shared objects and libraries127linker_exe linker used to create binary executables128archiver static library creator129130On platforms with a command-line (Unix, DOS/Windows), each of these131is a string that will be split into executable name and (optional)132list of arguments. (Splitting the string is done similarly to how133Unix shells operate: words are delimited by spaces, but quotes and134backslashes can override this. See135'distutils.util.split_quoted()'.)136"""137138# Note that some CCompiler implementation classes will define class139# attributes 'cpp', 'cc', etc. with hard-coded executable names;140# this is appropriate when a compiler class is for exactly one141# compiler/OS combination (eg. MSVCCompiler). Other compiler142# classes (UnixCCompiler, in particular) are driven by information143# discovered at run-time, since there are many different ways to do144# basically the same things with Unix C compilers.145146for key in kwargs:147if key not in self.executables:148raise ValueError("unknown executable '%s' for class %s" %149(key, self.__class__.__name__))150self.set_executable(key, kwargs[key])151152def set_executable(self, key, value):153if isinstance(value, str):154setattr(self, key, split_quoted(value))155else:156setattr(self, key, value)157158def _find_macro(self, name):159i = 0160for defn in self.macros:161if defn[0] == name:162return i163i += 1164return None165166def _check_macro_definitions(self, definitions):167"""Ensures that every element of 'definitions' is a valid macro168definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do169nothing if all definitions are OK, raise TypeError otherwise.170"""171for defn in definitions:172if not (isinstance(defn, tuple) and173(len(defn) in (1, 2) and174(isinstance (defn[1], str) or defn[1] is None)) and175isinstance (defn[0], str)):176raise TypeError(("invalid macro definition '%s': " % defn) + \177"must be tuple (string,), (string, string), or " + \178"(string, None)")179180181# -- Bookkeeping methods -------------------------------------------182183def define_macro(self, name, value=None):184"""Define a preprocessor macro for all compilations driven by this185compiler object. The optional parameter 'value' should be a186string; if it is not supplied, then the macro will be defined187without an explicit value and the exact outcome depends on the188compiler used (XXX true? does ANSI say anything about this?)189"""190# Delete from the list of macro definitions/undefinitions if191# already there (so that this one will take precedence).192i = self._find_macro (name)193if i is not None:194del self.macros[i]195196self.macros.append((name, value))197198def undefine_macro(self, name):199"""Undefine a preprocessor macro for all compilations driven by200this compiler object. If the same macro is defined by201'define_macro()' and undefined by 'undefine_macro()' the last call202takes precedence (including multiple redefinitions or203undefinitions). If the macro is redefined/undefined on a204per-compilation basis (ie. in the call to 'compile()'), then that205takes precedence.206"""207# Delete from the list of macro definitions/undefinitions if208# already there (so that this one will take precedence).209i = self._find_macro (name)210if i is not None:211del self.macros[i]212213undefn = (name,)214self.macros.append(undefn)215216def add_include_dir(self, dir):217"""Add 'dir' to the list of directories that will be searched for218header files. The compiler is instructed to search directories in219the order in which they are supplied by successive calls to220'add_include_dir()'.221"""222self.include_dirs.append(dir)223224def set_include_dirs(self, dirs):225"""Set the list of directories that will be searched to 'dirs' (a226list of strings). Overrides any preceding calls to227'add_include_dir()'; subsequence calls to 'add_include_dir()' add228to the list passed to 'set_include_dirs()'. This does not affect229any list of standard include directories that the compiler may230search by default.231"""232self.include_dirs = dirs[:]233234def add_library(self, libname):235"""Add 'libname' to the list of libraries that will be included in236all links driven by this compiler object. Note that 'libname'237should *not* be the name of a file containing a library, but the238name of the library itself: the actual filename will be inferred by239the linker, the compiler, or the compiler class (depending on the240platform).241242The linker will be instructed to link against libraries in the243order they were supplied to 'add_library()' and/or244'set_libraries()'. It is perfectly valid to duplicate library245names; the linker will be instructed to link against libraries as246many times as they are mentioned.247"""248self.libraries.append(libname)249250def set_libraries(self, libnames):251"""Set the list of libraries to be included in all links driven by252this compiler object to 'libnames' (a list of strings). This does253not affect any standard system libraries that the linker may254include by default.255"""256self.libraries = libnames[:]257258def add_library_dir(self, dir):259"""Add 'dir' to the list of directories that will be searched for260libraries specified to 'add_library()' and 'set_libraries()'. The261linker will be instructed to search for libraries in the order they262are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.263"""264self.library_dirs.append(dir)265266def set_library_dirs(self, dirs):267"""Set the list of library search directories to 'dirs' (a list of268strings). This does not affect any standard library search path269that the linker may search by default.270"""271self.library_dirs = dirs[:]272273def add_runtime_library_dir(self, dir):274"""Add 'dir' to the list of directories that will be searched for275shared libraries at runtime.276"""277self.runtime_library_dirs.append(dir)278279def set_runtime_library_dirs(self, dirs):280"""Set the list of directories to search for shared libraries at281runtime to 'dirs' (a list of strings). This does not affect any282standard search path that the runtime linker may search by283default.284"""285self.runtime_library_dirs = dirs[:]286287def add_link_object(self, object):288"""Add 'object' to the list of object files (or analogues, such as289explicitly named library files or the output of "resource290compilers") to be included in every link driven by this compiler291object.292"""293self.objects.append(object)294295def set_link_objects(self, objects):296"""Set the list of object files (or analogues) to be included in297every link to 'objects'. This does not affect any standard object298files that the linker may include by default (such as system299libraries).300"""301self.objects = objects[:]302303304# -- Private utility methods --------------------------------------305# (here for the convenience of subclasses)306307# Helper method to prep compiler in subclass compile() methods308309def _setup_compile(self, outdir, macros, incdirs, sources, depends,310extra):311"""Process arguments and decide which source files to compile."""312if outdir is None:313outdir = self.output_dir314elif not isinstance(outdir, str):315raise TypeError("'output_dir' must be a string or None")316317if macros is None:318macros = self.macros319elif isinstance(macros, list):320macros = macros + (self.macros or [])321else:322raise TypeError("'macros' (if supplied) must be a list of tuples")323324if incdirs is None:325incdirs = self.include_dirs326elif isinstance(incdirs, (list, tuple)):327incdirs = list(incdirs) + (self.include_dirs or [])328else:329raise TypeError(330"'include_dirs' (if supplied) must be a list of strings")331332if extra is None:333extra = []334335# Get the list of expected output (object) files336objects = self.object_filenames(sources, strip_dir=0,337output_dir=outdir)338assert len(objects) == len(sources)339340pp_opts = gen_preprocess_options(macros, incdirs)341342build = {}343for i in range(len(sources)):344src = sources[i]345obj = objects[i]346ext = os.path.splitext(src)[1]347self.mkpath(os.path.dirname(obj))348build[obj] = (src, ext)349350return macros, objects, extra, pp_opts, build351352def _get_cc_args(self, pp_opts, debug, before):353# works for unixccompiler, cygwinccompiler354cc_args = pp_opts + ['-c']355if debug:356cc_args[:0] = ['-g']357if before:358cc_args[:0] = before359return cc_args360361def _fix_compile_args(self, output_dir, macros, include_dirs):362"""Typecheck and fix-up some of the arguments to the 'compile()'363method, and return fixed-up values. Specifically: if 'output_dir'364is None, replaces it with 'self.output_dir'; ensures that 'macros'365is a list, and augments it with 'self.macros'; ensures that366'include_dirs' is a list, and augments it with 'self.include_dirs'.367Guarantees that the returned values are of the correct type,368i.e. for 'output_dir' either string or None, and for 'macros' and369'include_dirs' either list or None.370"""371if output_dir is None:372output_dir = self.output_dir373elif not isinstance(output_dir, str):374raise TypeError("'output_dir' must be a string or None")375376if macros is None:377macros = self.macros378elif isinstance(macros, list):379macros = macros + (self.macros or [])380else:381raise TypeError("'macros' (if supplied) must be a list of tuples")382383if include_dirs is None:384include_dirs = self.include_dirs385elif isinstance(include_dirs, (list, tuple)):386include_dirs = list(include_dirs) + (self.include_dirs or [])387else:388raise TypeError(389"'include_dirs' (if supplied) must be a list of strings")390391return output_dir, macros, include_dirs392393def _prep_compile(self, sources, output_dir, depends=None):394"""Decide which source files must be recompiled.395396Determine the list of object files corresponding to 'sources',397and figure out which ones really need to be recompiled.398Return a list of all object files and a dictionary telling399which source files can be skipped.400"""401# Get the list of expected output (object) files402objects = self.object_filenames(sources, output_dir=output_dir)403assert len(objects) == len(sources)404405# Return an empty dict for the "which source files can be skipped"406# return value to preserve API compatibility.407return objects, {}408409def _fix_object_args(self, objects, output_dir):410"""Typecheck and fix up some arguments supplied to various methods.411Specifically: ensure that 'objects' is a list; if output_dir is412None, replace with self.output_dir. Return fixed versions of413'objects' and 'output_dir'.414"""415if not isinstance(objects, (list, tuple)):416raise TypeError("'objects' must be a list or tuple of strings")417objects = list(objects)418419if output_dir is None:420output_dir = self.output_dir421elif not isinstance(output_dir, str):422raise TypeError("'output_dir' must be a string or None")423424return (objects, output_dir)425426def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):427"""Typecheck and fix up some of the arguments supplied to the428'link_*' methods. Specifically: ensure that all arguments are429lists, and augment them with their permanent versions430(eg. 'self.libraries' augments 'libraries'). Return a tuple with431fixed versions of all arguments.432"""433if libraries is None:434libraries = self.libraries435elif isinstance(libraries, (list, tuple)):436libraries = list (libraries) + (self.libraries or [])437else:438raise TypeError(439"'libraries' (if supplied) must be a list of strings")440441if library_dirs is None:442library_dirs = self.library_dirs443elif isinstance(library_dirs, (list, tuple)):444library_dirs = list (library_dirs) + (self.library_dirs or [])445else:446raise TypeError(447"'library_dirs' (if supplied) must be a list of strings")448449if runtime_library_dirs is None:450runtime_library_dirs = self.runtime_library_dirs451elif isinstance(runtime_library_dirs, (list, tuple)):452runtime_library_dirs = (list(runtime_library_dirs) +453(self.runtime_library_dirs or []))454else:455raise TypeError("'runtime_library_dirs' (if supplied) "456"must be a list of strings")457458return (libraries, library_dirs, runtime_library_dirs)459460def _need_link(self, objects, output_file):461"""Return true if we need to relink the files listed in 'objects'462to recreate 'output_file'.463"""464if self.force:465return True466else:467if self.dry_run:468newer = newer_group (objects, output_file, missing='newer')469else:470newer = newer_group (objects, output_file)471return newer472473def detect_language(self, sources):474"""Detect the language of a given file, or list of files. Uses475language_map, and language_order to do the job.476"""477if not isinstance(sources, list):478sources = [sources]479lang = None480index = len(self.language_order)481for source in sources:482base, ext = os.path.splitext(source)483extlang = self.language_map.get(ext)484try:485extindex = self.language_order.index(extlang)486if extindex < index:487lang = extlang488index = extindex489except ValueError:490pass491return lang492493494# -- Worker methods ------------------------------------------------495# (must be implemented by subclasses)496497def preprocess(self, source, output_file=None, macros=None,498include_dirs=None, extra_preargs=None, extra_postargs=None):499"""Preprocess a single C/C++ source file, named in 'source'.500Output will be written to file named 'output_file', or stdout if501'output_file' not supplied. 'macros' is a list of macro502definitions as for 'compile()', which will augment the macros set503with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a504list of directory names that will be added to the default list.505506Raises PreprocessError on failure.507"""508pass509510def compile(self, sources, output_dir=None, macros=None,511include_dirs=None, debug=0, extra_preargs=None,512extra_postargs=None, depends=None):513"""Compile one or more source files.514515'sources' must be a list of filenames, most likely C/C++516files, but in reality anything that can be handled by a517particular compiler and compiler class (eg. MSVCCompiler can518handle resource files in 'sources'). Return a list of object519filenames, one per source filename in 'sources'. Depending on520the implementation, not all source files will necessarily be521compiled, but all corresponding object filenames will be522returned.523524If 'output_dir' is given, object files will be put under it, while525retaining their original path component. That is, "foo/bar.c"526normally compiles to "foo/bar.o" (for a Unix implementation); if527'output_dir' is "build", then it would compile to528"build/foo/bar.o".529530'macros', if given, must be a list of macro definitions. A macro531definition is either a (name, value) 2-tuple or a (name,) 1-tuple.532The former defines a macro; if the value is None, the macro is533defined without an explicit value. The 1-tuple case undefines a534macro. Later definitions/redefinitions/ undefinitions take535precedence.536537'include_dirs', if given, must be a list of strings, the538directories to add to the default include file search path for this539compilation only.540541'debug' is a boolean; if true, the compiler will be instructed to542output debug symbols in (or alongside) the object file(s).543544'extra_preargs' and 'extra_postargs' are implementation- dependent.545On platforms that have the notion of a command-line (e.g. Unix,546DOS/Windows), they are most likely lists of strings: extra547command-line arguments to prepend/append to the compiler command548line. On other platforms, consult the implementation class549documentation. In any event, they are intended as an escape hatch550for those occasions when the abstract compiler framework doesn't551cut the mustard.552553'depends', if given, is a list of filenames that all targets554depend on. If a source file is older than any file in555depends, then the source file will be recompiled. This556supports dependency tracking, but only at a coarse557granularity.558559Raises CompileError on failure.560"""561# A concrete compiler class can either override this method562# entirely or implement _compile().563macros, objects, extra_postargs, pp_opts, build = \564self._setup_compile(output_dir, macros, include_dirs, sources,565depends, extra_postargs)566cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)567568for obj in objects:569try:570src, ext = build[obj]571except KeyError:572continue573self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)574575# Return *all* object filenames, not just the ones we just built.576return objects577578def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):579"""Compile 'src' to product 'obj'."""580# A concrete compiler class that does not override compile()581# should implement _compile().582pass583584def create_static_lib(self, objects, output_libname, output_dir=None,585debug=0, target_lang=None):586"""Link a bunch of stuff together to create a static library file.587The "bunch of stuff" consists of the list of object files supplied588as 'objects', the extra object files supplied to589'add_link_object()' and/or 'set_link_objects()', the libraries590supplied to 'add_library()' and/or 'set_libraries()', and the591libraries supplied as 'libraries' (if any).592593'output_libname' should be a library name, not a filename; the594filename will be inferred from the library name. 'output_dir' is595the directory where the library file will be put.596597'debug' is a boolean; if true, debugging information will be598included in the library (note that on most platforms, it is the599compile step where this matters: the 'debug' flag is included here600just for consistency).601602'target_lang' is the target language for which the given objects603are being compiled. This allows specific linkage time treatment of604certain languages.605606Raises LibError on failure.607"""608pass609610611# values for target_desc parameter in link()612SHARED_OBJECT = "shared_object"613SHARED_LIBRARY = "shared_library"614EXECUTABLE = "executable"615616def link(self,617target_desc,618objects,619output_filename,620output_dir=None,621libraries=None,622library_dirs=None,623runtime_library_dirs=None,624export_symbols=None,625debug=0,626extra_preargs=None,627extra_postargs=None,628build_temp=None,629target_lang=None):630"""Link a bunch of stuff together to create an executable or631shared library file.632633The "bunch of stuff" consists of the list of object files supplied634as 'objects'. 'output_filename' should be a filename. If635'output_dir' is supplied, 'output_filename' is relative to it636(i.e. 'output_filename' can provide directory components if637needed).638639'libraries' is a list of libraries to link against. These are640library names, not filenames, since they're translated into641filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"642on Unix and "foo.lib" on DOS/Windows). However, they can include a643directory component, which means the linker will look in that644specific directory rather than searching all the normal locations.645646'library_dirs', if supplied, should be a list of directories to647search for libraries that were specified as bare library names648(ie. no directory component). These are on top of the system649default and those supplied to 'add_library_dir()' and/or650'set_library_dirs()'. 'runtime_library_dirs' is a list of651directories that will be embedded into the shared library and used652to search for other shared libraries that *it* depends on at653run-time. (This may only be relevant on Unix.)654655'export_symbols' is a list of symbols that the shared library will656export. (This appears to be relevant only on Windows.)657658'debug' is as for 'compile()' and 'create_static_lib()', with the659slight distinction that it actually matters on most platforms (as660opposed to 'create_static_lib()', which includes a 'debug' flag661mostly for form's sake).662663'extra_preargs' and 'extra_postargs' are as for 'compile()' (except664of course that they supply command-line arguments for the665particular linker being used).666667'target_lang' is the target language for which the given objects668are being compiled. This allows specific linkage time treatment of669certain languages.670671Raises LinkError on failure.672"""673raise NotImplementedError674675676# Old 'link_*()' methods, rewritten to use the new 'link()' method.677678def link_shared_lib(self,679objects,680output_libname,681output_dir=None,682libraries=None,683library_dirs=None,684runtime_library_dirs=None,685export_symbols=None,686debug=0,687extra_preargs=None,688extra_postargs=None,689build_temp=None,690target_lang=None):691self.link(CCompiler.SHARED_LIBRARY, objects,692self.library_filename(output_libname, lib_type='shared'),693output_dir,694libraries, library_dirs, runtime_library_dirs,695export_symbols, debug,696extra_preargs, extra_postargs, build_temp, target_lang)697698699def link_shared_object(self,700objects,701output_filename,702output_dir=None,703libraries=None,704library_dirs=None,705runtime_library_dirs=None,706export_symbols=None,707debug=0,708extra_preargs=None,709extra_postargs=None,710build_temp=None,711target_lang=None):712self.link(CCompiler.SHARED_OBJECT, objects,713output_filename, output_dir,714libraries, library_dirs, runtime_library_dirs,715export_symbols, debug,716extra_preargs, extra_postargs, build_temp, target_lang)717718719def link_executable(self,720objects,721output_progname,722output_dir=None,723libraries=None,724library_dirs=None,725runtime_library_dirs=None,726debug=0,727extra_preargs=None,728extra_postargs=None,729target_lang=None):730self.link(CCompiler.EXECUTABLE, objects,731self.executable_filename(output_progname), output_dir,732libraries, library_dirs, runtime_library_dirs, None,733debug, extra_preargs, extra_postargs, None, target_lang)734735736# -- Miscellaneous methods -----------------------------------------737# These are all used by the 'gen_lib_options() function; there is738# no appropriate default implementation so subclasses should739# implement all of these.740741def library_dir_option(self, dir):742"""Return the compiler option to add 'dir' to the list of743directories searched for libraries.744"""745raise NotImplementedError746747def runtime_library_dir_option(self, dir):748"""Return the compiler option to add 'dir' to the list of749directories searched for runtime libraries.750"""751raise NotImplementedError752753def library_option(self, lib):754"""Return the compiler option to add 'lib' to the list of libraries755linked into the shared library or executable.756"""757raise NotImplementedError758759def has_function(self, funcname, includes=None, include_dirs=None,760libraries=None, library_dirs=None):761"""Return a boolean indicating whether funcname is supported on762the current platform. The optional arguments can be used to763augment the compilation environment.764"""765# this can't be included at module scope because it tries to766# import math which might not be available at that point - maybe767# the necessary logic should just be inlined?768import tempfile769if includes is None:770includes = []771if include_dirs is None:772include_dirs = []773if libraries is None:774libraries = []775if library_dirs is None:776library_dirs = []777fd, fname = tempfile.mkstemp(".c", funcname, text=True)778f = os.fdopen(fd, "w")779try:780for incl in includes:781f.write("""#include "%s"\n""" % incl)782f.write("""\783int main (int argc, char **argv) {784%s();785return 0;786}787""" % funcname)788finally:789f.close()790try:791objects = self.compile([fname], include_dirs=include_dirs)792except CompileError:793return False794finally:795os.remove(fname)796797try:798self.link_executable(objects, "a.out",799libraries=libraries,800library_dirs=library_dirs)801except (LinkError, TypeError):802return False803else:804os.remove(os.path.join(self.output_dir or '', "a.out"))805finally:806for fn in objects:807os.remove(fn)808return True809810def find_library_file (self, dirs, lib, debug=0):811"""Search the specified list of directories for a static or shared812library file 'lib' and return the full path to that file. If813'debug' true, look for a debugging version (if that makes sense on814the current platform). Return None if 'lib' wasn't found in any of815the specified directories.816"""817raise NotImplementedError818819# -- Filename generation methods -----------------------------------820821# The default implementation of the filename generating methods are822# prejudiced towards the Unix/DOS/Windows view of the world:823# * object files are named by replacing the source file extension824# (eg. .c/.cpp -> .o/.obj)825# * library files (shared or static) are named by plugging the826# library name and extension into a format string, eg.827# "lib%s.%s" % (lib_name, ".a") for Unix static libraries828# * executables are named by appending an extension (possibly829# empty) to the program name: eg. progname + ".exe" for830# Windows831#832# To reduce redundant code, these methods expect to find833# several attributes in the current object (presumably defined834# as class attributes):835# * src_extensions -836# list of C/C++ source file extensions, eg. ['.c', '.cpp']837# * obj_extension -838# object file extension, eg. '.o' or '.obj'839# * static_lib_extension -840# extension for static library files, eg. '.a' or '.lib'841# * shared_lib_extension -842# extension for shared library/object files, eg. '.so', '.dll'843# * static_lib_format -844# format string for generating static library filenames,845# eg. 'lib%s.%s' or '%s.%s'846# * shared_lib_format847# format string for generating shared library filenames848# (probably same as static_lib_format, since the extension849# is one of the intended parameters to the format string)850# * exe_extension -851# extension for executable files, eg. '' or '.exe'852853def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):854if output_dir is None:855output_dir = ''856obj_names = []857for src_name in source_filenames:858base, ext = os.path.splitext(src_name)859base = os.path.splitdrive(base)[1] # Chop off the drive860base = base[os.path.isabs(base):] # If abs, chop off leading /861if ext not in self.src_extensions:862raise UnknownFileError(863"unknown file type '%s' (from '%s')" % (ext, src_name))864if strip_dir:865base = os.path.basename(base)866obj_names.append(os.path.join(output_dir,867base + self.obj_extension))868return obj_names869870def shared_object_filename(self, basename, strip_dir=0, output_dir=''):871assert output_dir is not None872if strip_dir:873basename = os.path.basename(basename)874return os.path.join(output_dir, basename + self.shared_lib_extension)875876def executable_filename(self, basename, strip_dir=0, output_dir=''):877assert output_dir is not None878if strip_dir:879basename = os.path.basename(basename)880return os.path.join(output_dir, basename + (self.exe_extension or ''))881882def library_filename(self, libname, lib_type='static', # or 'shared'883strip_dir=0, output_dir=''):884assert output_dir is not None885if lib_type not in ("static", "shared", "dylib", "xcode_stub"):886raise ValueError(887"'lib_type' must be \"static\", \"shared\", \"dylib\", or \"xcode_stub\"")888fmt = getattr(self, lib_type + "_lib_format")889ext = getattr(self, lib_type + "_lib_extension")890891dir, base = os.path.split(libname)892filename = fmt % (base, ext)893if strip_dir:894dir = ''895896return os.path.join(output_dir, dir, filename)897898899# -- Utility methods -----------------------------------------------900901def announce(self, msg, level=1):902log.debug(msg)903904def debug_print(self, msg):905from distutils.debug import DEBUG906if DEBUG:907print(msg)908909def warn(self, msg):910sys.stderr.write("warning: %s\n" % msg)911912def execute(self, func, args, msg=None, level=1):913execute(func, args, msg, self.dry_run)914915def spawn(self, cmd, **kwargs):916spawn(cmd, dry_run=self.dry_run, **kwargs)917918def move_file(self, src, dst):919return move_file(src, dst, dry_run=self.dry_run)920921def mkpath (self, name, mode=0o777):922mkpath(name, mode, dry_run=self.dry_run)923924925# Map a sys.platform/os.name ('posix', 'nt') to the default compiler926# type for that platform. Keys are interpreted as re match927# patterns. Order is important; platform mappings are preferred over928# OS names.929_default_compilers = (930931# Platform string mappings932933# on a cygwin built python we can use gcc like an ordinary UNIXish934# compiler935('cygwin.*', 'unix'),936937# OS name mappings938('posix', 'unix'),939('nt', 'msvc'),940941)942943def get_default_compiler(osname=None, platform=None):944"""Determine the default compiler to use for the given platform.945946osname should be one of the standard Python OS names (i.e. the947ones returned by os.name) and platform the common value948returned by sys.platform for the platform in question.949950The default values are os.name and sys.platform in case the951parameters are not given.952"""953if osname is None:954osname = os.name955if platform is None:956platform = sys.platform957for pattern, compiler in _default_compilers:958if re.match(pattern, platform) is not None or \959re.match(pattern, osname) is not None:960return compiler961# Default to Unix compiler962return 'unix'963964# Map compiler types to (module_name, class_name) pairs -- ie. where to965# find the code that implements an interface to this compiler. (The module966# is assumed to be in the 'distutils' package.)967compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler',968"standard UNIX-style compiler"),969'msvc': ('_msvccompiler', 'MSVCCompiler',970"Microsoft Visual C++"),971'cygwin': ('cygwinccompiler', 'CygwinCCompiler',972"Cygwin port of GNU C Compiler for Win32"),973'mingw32': ('cygwinccompiler', 'Mingw32CCompiler',974"Mingw32 port of GNU C Compiler for Win32"),975'bcpp': ('bcppcompiler', 'BCPPCompiler',976"Borland C++ Compiler"),977}978979def show_compilers():980"""Print list of available compilers (used by the "--help-compiler"981options to "build", "build_ext", "build_clib").982"""983# XXX this "knows" that the compiler option it's describing is984# "--compiler", which just happens to be the case for the three985# commands that use it.986from distutils.fancy_getopt import FancyGetopt987compilers = []988for compiler in compiler_class.keys():989compilers.append(("compiler="+compiler, None,990compiler_class[compiler][2]))991compilers.sort()992pretty_printer = FancyGetopt(compilers)993pretty_printer.print_help("List of available compilers:")994995996def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):997"""Generate an instance of some CCompiler subclass for the supplied998platform/compiler combination. 'plat' defaults to 'os.name'999(eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler1000for that platform. Currently only 'posix' and 'nt' are supported, and1001the default compilers are "traditional Unix interface" (UnixCCompiler1002class) and Visual C++ (MSVCCompiler class). Note that it's perfectly1003possible to ask for a Unix compiler object under Windows, and a1004Microsoft compiler object under Unix -- if you supply a value for1005'compiler', 'plat' is ignored.1006"""1007if plat is None:1008plat = os.name10091010try:1011if compiler is None:1012compiler = get_default_compiler(plat)10131014(module_name, class_name, long_description) = compiler_class[compiler]1015except KeyError:1016msg = "don't know how to compile C/C++ code on platform '%s'" % plat1017if compiler is not None:1018msg = msg + " with '%s' compiler" % compiler1019raise DistutilsPlatformError(msg)10201021try:1022module_name = "distutils." + module_name1023__import__ (module_name)1024module = sys.modules[module_name]1025klass = vars(module)[class_name]1026except ImportError:1027raise DistutilsModuleError(1028"can't compile C/C++ code: unable to load module '%s'" % \1029module_name)1030except KeyError:1031raise DistutilsModuleError(1032"can't compile C/C++ code: unable to find class '%s' "1033"in module '%s'" % (class_name, module_name))10341035# XXX The None is necessary to preserve backwards compatibility1036# with classes that expect verbose to be the first positional1037# argument.1038return klass(None, dry_run, force)103910401041def gen_preprocess_options(macros, include_dirs):1042"""Generate C pre-processor options (-D, -U, -I) as used by at least1043two types of compilers: the typical Unix compiler and Visual C++.1044'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)1045means undefine (-U) macro 'name', and (name,value) means define (-D)1046macro 'name' to 'value'. 'include_dirs' is just a list of directory1047names to be added to the header file search path (-I). Returns a list1048of command-line options suitable for either Unix compilers or Visual1049C++.1050"""1051# XXX it would be nice (mainly aesthetic, and so we don't generate1052# stupid-looking command lines) to go over 'macros' and eliminate1053# redundant definitions/undefinitions (ie. ensure that only the1054# latest mention of a particular macro winds up on the command1055# line). I don't think it's essential, though, since most (all?)1056# Unix C compilers only pay attention to the latest -D or -U1057# mention of a macro on their command line. Similar situation for1058# 'include_dirs'. I'm punting on both for now. Anyways, weeding out1059# redundancies like this should probably be the province of1060# CCompiler, since the data structures used are inherited from it1061# and therefore common to all CCompiler classes.1062pp_opts = []1063for macro in macros:1064if not (isinstance(macro, tuple) and 1 <= len(macro) <= 2):1065raise TypeError(1066"bad macro definition '%s': "1067"each element of 'macros' list must be a 1- or 2-tuple"1068% macro)10691070if len(macro) == 1: # undefine this macro1071pp_opts.append("-U%s" % macro[0])1072elif len(macro) == 2:1073if macro[1] is None: # define with no explicit value1074pp_opts.append("-D%s" % macro[0])1075else:1076# XXX *don't* need to be clever about quoting the1077# macro value here, because we're going to avoid the1078# shell at all costs when we spawn the command!1079pp_opts.append("-D%s=%s" % macro)10801081for dir in include_dirs:1082pp_opts.append("-I%s" % dir)1083return pp_opts108410851086def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):1087"""Generate linker options for searching library directories and1088linking with specific libraries. 'libraries' and 'library_dirs' are,1089respectively, lists of library names (not filenames!) and search1090directories. Returns a list of command-line options suitable for use1091with some compiler (depending on the two format strings passed in).1092"""1093lib_opts = []10941095for dir in library_dirs:1096lib_opts.append(compiler.library_dir_option(dir))10971098for dir in runtime_library_dirs:1099opt = compiler.runtime_library_dir_option(dir)1100if isinstance(opt, list):1101lib_opts = lib_opts + opt1102else:1103lib_opts.append(opt)11041105# XXX it's important that we *not* remove redundant library mentions!1106# sometimes you really do have to say "-lfoo -lbar -lfoo" in order to1107# resolve all symbols. I just hope we never have to say "-lfoo obj.o1108# -lbar" to get things to work -- that's certainly a possibility, but a1109# pretty nasty way to arrange your C code.11101111for lib in libraries:1112(lib_dir, lib_name) = os.path.split(lib)1113if lib_dir:1114lib_file = compiler.find_library_file([lib_dir], lib_name)1115if lib_file:1116lib_opts.append(lib_file)1117else:1118compiler.warn("no library file corresponding to "1119"'%s' found (skipping)" % lib)1120else:1121lib_opts.append(compiler.library_option (lib))1122return lib_opts112311241125