+++ /dev/null
-"""distutils.ccompiler\r
-\r
-Contains CCompiler, an abstract base class that defines the interface\r
-for the Distutils compiler abstraction model."""\r
-\r
-__revision__ = "$Id$"\r
-\r
-import sys\r
-import os\r
-import re\r
-\r
-from distutils.errors import (CompileError, LinkError, UnknownFileError,\r
- DistutilsPlatformError, DistutilsModuleError)\r
-from distutils.spawn import spawn\r
-from distutils.file_util import move_file\r
-from distutils.dir_util import mkpath\r
-from distutils.dep_util import newer_group\r
-from distutils.util import split_quoted, execute\r
-from distutils import log\r
-\r
-_sysconfig = __import__('sysconfig')\r
-\r
-def customize_compiler(compiler):\r
- """Do any platform-specific customization of a CCompiler instance.\r
-\r
- Mainly needed on Unix, so we can plug in the information that\r
- varies across Unices and is stored in Python's Makefile.\r
- """\r
- if compiler.compiler_type == "unix":\r
- (cc, cxx, opt, cflags, ccshared, ldshared, so_ext, ar, ar_flags) = \\r
- _sysconfig.get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS',\r
- 'CCSHARED', 'LDSHARED', 'SO', 'AR',\r
- 'ARFLAGS')\r
-\r
- if 'CC' in os.environ:\r
- cc = os.environ['CC']\r
- if 'CXX' in os.environ:\r
- cxx = os.environ['CXX']\r
- if 'LDSHARED' in os.environ:\r
- ldshared = os.environ['LDSHARED']\r
- if 'CPP' in os.environ:\r
- cpp = os.environ['CPP']\r
- else:\r
- cpp = cc + " -E" # not always\r
- if 'LDFLAGS' in os.environ:\r
- ldshared = ldshared + ' ' + os.environ['LDFLAGS']\r
- if 'CFLAGS' in os.environ:\r
- cflags = opt + ' ' + os.environ['CFLAGS']\r
- ldshared = ldshared + ' ' + os.environ['CFLAGS']\r
- if 'CPPFLAGS' in os.environ:\r
- cpp = cpp + ' ' + os.environ['CPPFLAGS']\r
- cflags = cflags + ' ' + os.environ['CPPFLAGS']\r
- ldshared = ldshared + ' ' + os.environ['CPPFLAGS']\r
- if 'AR' in os.environ:\r
- ar = os.environ['AR']\r
- if 'ARFLAGS' in os.environ:\r
- archiver = ar + ' ' + os.environ['ARFLAGS']\r
- else:\r
- archiver = ar + ' ' + ar_flags\r
-\r
- cc_cmd = cc + ' ' + cflags\r
- compiler.set_executables(\r
- preprocessor=cpp,\r
- compiler=cc_cmd,\r
- compiler_so=cc_cmd + ' ' + ccshared,\r
- compiler_cxx=cxx,\r
- linker_so=ldshared,\r
- linker_exe=cc,\r
- archiver=archiver)\r
-\r
- compiler.shared_lib_extension = so_ext\r
-\r
-class CCompiler:\r
- """Abstract base class to define the interface that must be implemented\r
- by real compiler classes. Also has some utility methods used by\r
- several compiler classes.\r
-\r
- The basic idea behind a compiler abstraction class is that each\r
- instance can be used for all the compile/link steps in building a\r
- single project. Thus, attributes common to all of those compile and\r
- link steps -- include directories, macros to define, libraries to link\r
- against, etc. -- are attributes of the compiler instance. To allow for\r
- variability in how individual files are treated, most of those\r
- attributes may be varied on a per-compilation or per-link basis.\r
- """\r
-\r
- # 'compiler_type' is a class attribute that identifies this class. It\r
- # keeps code that wants to know what kind of compiler it's dealing with\r
- # from having to import all possible compiler classes just to do an\r
- # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type'\r
- # should really, really be one of the keys of the 'compiler_class'\r
- # dictionary (see below -- used by the 'new_compiler()' factory\r
- # function) -- authors of new compiler interface classes are\r
- # responsible for updating 'compiler_class'!\r
- compiler_type = None\r
-\r
- # XXX things not handled by this compiler abstraction model:\r
- # * client can't provide additional options for a compiler,\r
- # e.g. warning, optimization, debugging flags. Perhaps this\r
- # should be the domain of concrete compiler abstraction classes\r
- # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base\r
- # class should have methods for the common ones.\r
- # * can't completely override the include or library searchg\r
- # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".\r
- # I'm not sure how widely supported this is even by Unix\r
- # compilers, much less on other platforms. And I'm even less\r
- # sure how useful it is; maybe for cross-compiling, but\r
- # support for that is a ways off. (And anyways, cross\r
- # compilers probably have a dedicated binary with the\r
- # right paths compiled in. I hope.)\r
- # * can't do really freaky things with the library list/library\r
- # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against\r
- # different versions of libfoo.a in different locations. I\r
- # think this is useless without the ability to null out the\r
- # library search path anyways.\r
-\r
-\r
- # Subclasses that rely on the standard filename generation methods\r
- # implemented below should override these; see the comment near\r
- # those methods ('object_filenames()' et. al.) for details:\r
- src_extensions = None # list of strings\r
- obj_extension = None # string\r
- static_lib_extension = None\r
- shared_lib_extension = None # string\r
- static_lib_format = None # format string\r
- shared_lib_format = None # prob. same as static_lib_format\r
- exe_extension = None # string\r
-\r
- # Default language settings. language_map is used to detect a source\r
- # file or Extension target language, checking source filenames.\r
- # language_order is used to detect the language precedence, when deciding\r
- # what language to use when mixing source types. For example, if some\r
- # extension has two files with ".c" extension, and one with ".cpp", it\r
- # is still linked as c++.\r
- language_map = {".c" : "c",\r
- ".cc" : "c++",\r
- ".cpp" : "c++",\r
- ".cxx" : "c++",\r
- ".m" : "objc",\r
- }\r
- language_order = ["c++", "objc", "c"]\r
-\r
- def __init__ (self, verbose=0, dry_run=0, force=0):\r
- self.dry_run = dry_run\r
- self.force = force\r
- self.verbose = verbose\r
-\r
- # 'output_dir': a common output directory for object, library,\r
- # shared object, and shared library files\r
- self.output_dir = None\r
-\r
- # 'macros': a list of macro definitions (or undefinitions). A\r
- # macro definition is a 2-tuple (name, value), where the value is\r
- # either a string or None (no explicit value). A macro\r
- # undefinition is a 1-tuple (name,).\r
- self.macros = []\r
-\r
- # 'include_dirs': a list of directories to search for include files\r
- self.include_dirs = []\r
-\r
- # 'libraries': a list of libraries to include in any link\r
- # (library names, not filenames: eg. "foo" not "libfoo.a")\r
- self.libraries = []\r
-\r
- # 'library_dirs': a list of directories to search for libraries\r
- self.library_dirs = []\r
-\r
- # 'runtime_library_dirs': a list of directories to search for\r
- # shared libraries/objects at runtime\r
- self.runtime_library_dirs = []\r
-\r
- # 'objects': a list of object files (or similar, such as explicitly\r
- # named library files) to include on any link\r
- self.objects = []\r
-\r
- for key in self.executables.keys():\r
- self.set_executable(key, self.executables[key])\r
-\r
- def set_executables(self, **args):\r
- """Define the executables (and options for them) that will be run\r
- to perform the various stages of compilation. The exact set of\r
- executables that may be specified here depends on the compiler\r
- class (via the 'executables' class attribute), but most will have:\r
- compiler the C/C++ compiler\r
- linker_so linker used to create shared objects and libraries\r
- linker_exe linker used to create binary executables\r
- archiver static library creator\r
-\r
- On platforms with a command-line (Unix, DOS/Windows), each of these\r
- is a string that will be split into executable name and (optional)\r
- list of arguments. (Splitting the string is done similarly to how\r
- Unix shells operate: words are delimited by spaces, but quotes and\r
- backslashes can override this. See\r
- 'distutils.util.split_quoted()'.)\r
- """\r
-\r
- # Note that some CCompiler implementation classes will define class\r
- # attributes 'cpp', 'cc', etc. with hard-coded executable names;\r
- # this is appropriate when a compiler class is for exactly one\r
- # compiler/OS combination (eg. MSVCCompiler). Other compiler\r
- # classes (UnixCCompiler, in particular) are driven by information\r
- # discovered at run-time, since there are many different ways to do\r
- # basically the same things with Unix C compilers.\r
-\r
- for key in args.keys():\r
- if key not in self.executables:\r
- raise ValueError, \\r
- "unknown executable '%s' for class %s" % \\r
- (key, self.__class__.__name__)\r
- self.set_executable(key, args[key])\r
-\r
- def set_executable(self, key, value):\r
- if isinstance(value, str):\r
- setattr(self, key, split_quoted(value))\r
- else:\r
- setattr(self, key, value)\r
-\r
- def _find_macro(self, name):\r
- i = 0\r
- for defn in self.macros:\r
- if defn[0] == name:\r
- return i\r
- i = i + 1\r
- return None\r
-\r
- def _check_macro_definitions(self, definitions):\r
- """Ensures that every element of 'definitions' is a valid macro\r
- definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do\r
- nothing if all definitions are OK, raise TypeError otherwise.\r
- """\r
- for defn in definitions:\r
- if not (isinstance(defn, tuple) and\r
- (len (defn) == 1 or\r
- (len (defn) == 2 and\r
- (isinstance(defn[1], str) or defn[1] is None))) and\r
- isinstance(defn[0], str)):\r
- raise TypeError, \\r
- ("invalid macro definition '%s': " % defn) + \\r
- "must be tuple (string,), (string, string), or " + \\r
- "(string, None)"\r
-\r
-\r
- # -- Bookkeeping methods -------------------------------------------\r
-\r
- def define_macro(self, name, value=None):\r
- """Define a preprocessor macro for all compilations driven by this\r
- compiler object. The optional parameter 'value' should be a\r
- string; if it is not supplied, then the macro will be defined\r
- without an explicit value and the exact outcome depends on the\r
- compiler used (XXX true? does ANSI say anything about this?)\r
- """\r
- # Delete from the list of macro definitions/undefinitions if\r
- # already there (so that this one will take precedence).\r
- i = self._find_macro (name)\r
- if i is not None:\r
- del self.macros[i]\r
-\r
- defn = (name, value)\r
- self.macros.append (defn)\r
-\r
- def undefine_macro(self, name):\r
- """Undefine a preprocessor macro for all compilations driven by\r
- this compiler object. If the same macro is defined by\r
- 'define_macro()' and undefined by 'undefine_macro()' the last call\r
- takes precedence (including multiple redefinitions or\r
- undefinitions). If the macro is redefined/undefined on a\r
- per-compilation basis (ie. in the call to 'compile()'), then that\r
- takes precedence.\r
- """\r
- # Delete from the list of macro definitions/undefinitions if\r
- # already there (so that this one will take precedence).\r
- i = self._find_macro (name)\r
- if i is not None:\r
- del self.macros[i]\r
-\r
- undefn = (name,)\r
- self.macros.append (undefn)\r
-\r
- def add_include_dir(self, dir):\r
- """Add 'dir' to the list of directories that will be searched for\r
- header files. The compiler is instructed to search directories in\r
- the order in which they are supplied by successive calls to\r
- 'add_include_dir()'.\r
- """\r
- self.include_dirs.append (dir)\r
-\r
- def set_include_dirs(self, dirs):\r
- """Set the list of directories that will be searched to 'dirs' (a\r
- list of strings). Overrides any preceding calls to\r
- 'add_include_dir()'; subsequence calls to 'add_include_dir()' add\r
- to the list passed to 'set_include_dirs()'. This does not affect\r
- any list of standard include directories that the compiler may\r
- search by default.\r
- """\r
- self.include_dirs = dirs[:]\r
-\r
- def add_library(self, libname):\r
- """Add 'libname' to the list of libraries that will be included in\r
- all links driven by this compiler object. Note that 'libname'\r
- should *not* be the name of a file containing a library, but the\r
- name of the library itself: the actual filename will be inferred by\r
- the linker, the compiler, or the compiler class (depending on the\r
- platform).\r
-\r
- The linker will be instructed to link against libraries in the\r
- order they were supplied to 'add_library()' and/or\r
- 'set_libraries()'. It is perfectly valid to duplicate library\r
- names; the linker will be instructed to link against libraries as\r
- many times as they are mentioned.\r
- """\r
- self.libraries.append (libname)\r
-\r
- def set_libraries(self, libnames):\r
- """Set the list of libraries to be included in all links driven by\r
- this compiler object to 'libnames' (a list of strings). This does\r
- not affect any standard system libraries that the linker may\r
- include by default.\r
- """\r
- self.libraries = libnames[:]\r
-\r
-\r
- def add_library_dir(self, dir):\r
- """Add 'dir' to the list of directories that will be searched for\r
- libraries specified to 'add_library()' and 'set_libraries()'. The\r
- linker will be instructed to search for libraries in the order they\r
- are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.\r
- """\r
- self.library_dirs.append(dir)\r
-\r
- def set_library_dirs(self, dirs):\r
- """Set the list of library search directories to 'dirs' (a list of\r
- strings). This does not affect any standard library search path\r
- that the linker may search by default.\r
- """\r
- self.library_dirs = dirs[:]\r
-\r
- def add_runtime_library_dir(self, dir):\r
- """Add 'dir' to the list of directories that will be searched for\r
- shared libraries at runtime.\r
- """\r
- self.runtime_library_dirs.append(dir)\r
-\r
- def set_runtime_library_dirs(self, dirs):\r
- """Set the list of directories to search for shared libraries at\r
- runtime to 'dirs' (a list of strings). This does not affect any\r
- standard search path that the runtime linker may search by\r
- default.\r
- """\r
- self.runtime_library_dirs = dirs[:]\r
-\r
- def add_link_object(self, object):\r
- """Add 'object' to the list of object files (or analogues, such as\r
- explicitly named library files or the output of "resource\r
- compilers") to be included in every link driven by this compiler\r
- object.\r
- """\r
- self.objects.append(object)\r
-\r
- def set_link_objects(self, objects):\r
- """Set the list of object files (or analogues) to be included in\r
- every link to 'objects'. This does not affect any standard object\r
- files that the linker may include by default (such as system\r
- libraries).\r
- """\r
- self.objects = objects[:]\r
-\r
-\r
- # -- Private utility methods --------------------------------------\r
- # (here for the convenience of subclasses)\r
-\r
- # Helper method to prep compiler in subclass compile() methods\r
-\r
- def _setup_compile(self, outdir, macros, incdirs, sources, depends,\r
- extra):\r
- """Process arguments and decide which source files to compile."""\r
- if outdir is None:\r
- outdir = self.output_dir\r
- elif not isinstance(outdir, str):\r
- raise TypeError, "'output_dir' must be a string or None"\r
-\r
- if macros is None:\r
- macros = self.macros\r
- elif isinstance(macros, list):\r
- macros = macros + (self.macros or [])\r
- else:\r
- raise TypeError, "'macros' (if supplied) must be a list of tuples"\r
-\r
- if incdirs is None:\r
- incdirs = self.include_dirs\r
- elif isinstance(incdirs, (list, tuple)):\r
- incdirs = list(incdirs) + (self.include_dirs or [])\r
- else:\r
- raise TypeError, \\r
- "'include_dirs' (if supplied) must be a list of strings"\r
-\r
- if extra is None:\r
- extra = []\r
-\r
- # Get the list of expected output (object) files\r
- objects = self.object_filenames(sources,\r
- strip_dir=0,\r
- output_dir=outdir)\r
- assert len(objects) == len(sources)\r
-\r
- pp_opts = gen_preprocess_options(macros, incdirs)\r
-\r
- build = {}\r
- for i in range(len(sources)):\r
- src = sources[i]\r
- obj = objects[i]\r
- ext = os.path.splitext(src)[1]\r
- self.mkpath(os.path.dirname(obj))\r
- build[obj] = (src, ext)\r
-\r
- return macros, objects, extra, pp_opts, build\r
-\r
- def _get_cc_args(self, pp_opts, debug, before):\r
- # works for unixccompiler, emxccompiler, cygwinccompiler\r
- cc_args = pp_opts + ['-c']\r
- if debug:\r
- cc_args[:0] = ['-g']\r
- if before:\r
- cc_args[:0] = before\r
- return cc_args\r
-\r
- def _fix_compile_args(self, output_dir, macros, include_dirs):\r
- """Typecheck and fix-up some of the arguments to the 'compile()'\r
- method, and return fixed-up values. Specifically: if 'output_dir'\r
- is None, replaces it with 'self.output_dir'; ensures that 'macros'\r
- is a list, and augments it with 'self.macros'; ensures that\r
- 'include_dirs' is a list, and augments it with 'self.include_dirs'.\r
- Guarantees that the returned values are of the correct type,\r
- i.e. for 'output_dir' either string or None, and for 'macros' and\r
- 'include_dirs' either list or None.\r
- """\r
- if output_dir is None:\r
- output_dir = self.output_dir\r
- elif not isinstance(output_dir, str):\r
- raise TypeError, "'output_dir' must be a string or None"\r
-\r
- if macros is None:\r
- macros = self.macros\r
- elif isinstance(macros, list):\r
- macros = macros + (self.macros or [])\r
- else:\r
- raise TypeError, "'macros' (if supplied) must be a list of tuples"\r
-\r
- if include_dirs is None:\r
- include_dirs = self.include_dirs\r
- elif isinstance(include_dirs, (list, tuple)):\r
- include_dirs = list (include_dirs) + (self.include_dirs or [])\r
- else:\r
- raise TypeError, \\r
- "'include_dirs' (if supplied) must be a list of strings"\r
-\r
- return output_dir, macros, include_dirs\r
-\r
- def _fix_object_args(self, objects, output_dir):\r
- """Typecheck and fix up some arguments supplied to various methods.\r
- Specifically: ensure that 'objects' is a list; if output_dir is\r
- None, replace with self.output_dir. Return fixed versions of\r
- 'objects' and 'output_dir'.\r
- """\r
- if not isinstance(objects, (list, tuple)):\r
- raise TypeError, \\r
- "'objects' must be a list or tuple of strings"\r
- objects = list (objects)\r
-\r
- if output_dir is None:\r
- output_dir = self.output_dir\r
- elif not isinstance(output_dir, str):\r
- raise TypeError, "'output_dir' must be a string or None"\r
-\r
- return (objects, output_dir)\r
-\r
- def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):\r
- """Typecheck and fix up some of the arguments supplied to the\r
- 'link_*' methods. Specifically: ensure that all arguments are\r
- lists, and augment them with their permanent versions\r
- (eg. 'self.libraries' augments 'libraries'). Return a tuple with\r
- fixed versions of all arguments.\r
- """\r
- if libraries is None:\r
- libraries = self.libraries\r
- elif isinstance(libraries, (list, tuple)):\r
- libraries = list (libraries) + (self.libraries or [])\r
- else:\r
- raise TypeError, \\r
- "'libraries' (if supplied) must be a list of strings"\r
-\r
- if library_dirs is None:\r
- library_dirs = self.library_dirs\r
- elif isinstance(library_dirs, (list, tuple)):\r
- library_dirs = list (library_dirs) + (self.library_dirs or [])\r
- else:\r
- raise TypeError, \\r
- "'library_dirs' (if supplied) must be a list of strings"\r
-\r
- if runtime_library_dirs is None:\r
- runtime_library_dirs = self.runtime_library_dirs\r
- elif isinstance(runtime_library_dirs, (list, tuple)):\r
- runtime_library_dirs = (list (runtime_library_dirs) +\r
- (self.runtime_library_dirs or []))\r
- else:\r
- raise TypeError, \\r
- "'runtime_library_dirs' (if supplied) " + \\r
- "must be a list of strings"\r
-\r
- return (libraries, library_dirs, runtime_library_dirs)\r
-\r
- def _need_link(self, objects, output_file):\r
- """Return true if we need to relink the files listed in 'objects'\r
- to recreate 'output_file'.\r
- """\r
- if self.force:\r
- return 1\r
- else:\r
- if self.dry_run:\r
- newer = newer_group (objects, output_file, missing='newer')\r
- else:\r
- newer = newer_group (objects, output_file)\r
- return newer\r
-\r
- def detect_language(self, sources):\r
- """Detect the language of a given file, or list of files. Uses\r
- language_map, and language_order to do the job.\r
- """\r
- if not isinstance(sources, list):\r
- sources = [sources]\r
- lang = None\r
- index = len(self.language_order)\r
- for source in sources:\r
- base, ext = os.path.splitext(source)\r
- extlang = self.language_map.get(ext)\r
- try:\r
- extindex = self.language_order.index(extlang)\r
- if extindex < index:\r
- lang = extlang\r
- index = extindex\r
- except ValueError:\r
- pass\r
- return lang\r
-\r
- # -- Worker methods ------------------------------------------------\r
- # (must be implemented by subclasses)\r
-\r
- def preprocess(self, source, output_file=None, macros=None,\r
- include_dirs=None, extra_preargs=None, extra_postargs=None):\r
- """Preprocess a single C/C++ source file, named in 'source'.\r
- Output will be written to file named 'output_file', or stdout if\r
- 'output_file' not supplied. 'macros' is a list of macro\r
- definitions as for 'compile()', which will augment the macros set\r
- with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a\r
- list of directory names that will be added to the default list.\r
-\r
- Raises PreprocessError on failure.\r
- """\r
- pass\r
-\r
- def compile(self, sources, output_dir=None, macros=None,\r
- include_dirs=None, debug=0, extra_preargs=None,\r
- extra_postargs=None, depends=None):\r
- """Compile one or more source files.\r
-\r
- 'sources' must be a list of filenames, most likely C/C++\r
- files, but in reality anything that can be handled by a\r
- particular compiler and compiler class (eg. MSVCCompiler can\r
- handle resource files in 'sources'). Return a list of object\r
- filenames, one per source filename in 'sources'. Depending on\r
- the implementation, not all source files will necessarily be\r
- compiled, but all corresponding object filenames will be\r
- returned.\r
-\r
- If 'output_dir' is given, object files will be put under it, while\r
- retaining their original path component. That is, "foo/bar.c"\r
- normally compiles to "foo/bar.o" (for a Unix implementation); if\r
- 'output_dir' is "build", then it would compile to\r
- "build/foo/bar.o".\r
-\r
- 'macros', if given, must be a list of macro definitions. A macro\r
- definition is either a (name, value) 2-tuple or a (name,) 1-tuple.\r
- The former defines a macro; if the value is None, the macro is\r
- defined without an explicit value. The 1-tuple case undefines a\r
- macro. Later definitions/redefinitions/ undefinitions take\r
- precedence.\r
-\r
- 'include_dirs', if given, must be a list of strings, the\r
- directories to add to the default include file search path for this\r
- compilation only.\r
-\r
- 'debug' is a boolean; if true, the compiler will be instructed to\r
- output debug symbols in (or alongside) the object file(s).\r
-\r
- 'extra_preargs' and 'extra_postargs' are implementation- dependent.\r
- On platforms that have the notion of a command-line (e.g. Unix,\r
- DOS/Windows), they are most likely lists of strings: extra\r
- command-line arguments to prepand/append to the compiler command\r
- line. On other platforms, consult the implementation class\r
- documentation. In any event, they are intended as an escape hatch\r
- for those occasions when the abstract compiler framework doesn't\r
- cut the mustard.\r
-\r
- 'depends', if given, is a list of filenames that all targets\r
- depend on. If a source file is older than any file in\r
- depends, then the source file will be recompiled. This\r
- supports dependency tracking, but only at a coarse\r
- granularity.\r
-\r
- Raises CompileError on failure.\r
- """\r
- # A concrete compiler class can either override this method\r
- # entirely or implement _compile().\r
-\r
- macros, objects, extra_postargs, pp_opts, build = \\r
- self._setup_compile(output_dir, macros, include_dirs, sources,\r
- depends, extra_postargs)\r
- cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)\r
-\r
- for obj in objects:\r
- try:\r
- src, ext = build[obj]\r
- except KeyError:\r
- continue\r
- self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)\r
-\r
- # Return *all* object filenames, not just the ones we just built.\r
- return objects\r
-\r
- def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):\r
- """Compile 'src' to product 'obj'."""\r
-\r
- # A concrete compiler class that does not override compile()\r
- # should implement _compile().\r
- pass\r
-\r
- def create_static_lib(self, objects, output_libname, output_dir=None,\r
- debug=0, target_lang=None):\r
- """Link a bunch of stuff together to create a static library file.\r
- The "bunch of stuff" consists of the list of object files supplied\r
- as 'objects', the extra object files supplied to\r
- 'add_link_object()' and/or 'set_link_objects()', the libraries\r
- supplied to 'add_library()' and/or 'set_libraries()', and the\r
- libraries supplied as 'libraries' (if any).\r
-\r
- 'output_libname' should be a library name, not a filename; the\r
- filename will be inferred from the library name. 'output_dir' is\r
- the directory where the library file will be put.\r
-\r
- 'debug' is a boolean; if true, debugging information will be\r
- included in the library (note that on most platforms, it is the\r
- compile step where this matters: the 'debug' flag is included here\r
- just for consistency).\r
-\r
- 'target_lang' is the target language for which the given objects\r
- are being compiled. This allows specific linkage time treatment of\r
- certain languages.\r
-\r
- Raises LibError on failure.\r
- """\r
- pass\r
-\r
- # values for target_desc parameter in link()\r
- SHARED_OBJECT = "shared_object"\r
- SHARED_LIBRARY = "shared_library"\r
- EXECUTABLE = "executable"\r
-\r
- def link(self, target_desc, objects, output_filename, output_dir=None,\r
- libraries=None, library_dirs=None, runtime_library_dirs=None,\r
- export_symbols=None, debug=0, extra_preargs=None,\r
- extra_postargs=None, build_temp=None, target_lang=None):\r
- """Link a bunch of stuff together to create an executable or\r
- shared library file.\r
-\r
- The "bunch of stuff" consists of the list of object files supplied\r
- as 'objects'. 'output_filename' should be a filename. If\r
- 'output_dir' is supplied, 'output_filename' is relative to it\r
- (i.e. 'output_filename' can provide directory components if\r
- needed).\r
-\r
- 'libraries' is a list of libraries to link against. These are\r
- library names, not filenames, since they're translated into\r
- filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"\r
- on Unix and "foo.lib" on DOS/Windows). However, they can include a\r
- directory component, which means the linker will look in that\r
- specific directory rather than searching all the normal locations.\r
-\r
- 'library_dirs', if supplied, should be a list of directories to\r
- search for libraries that were specified as bare library names\r
- (ie. no directory component). These are on top of the system\r
- default and those supplied to 'add_library_dir()' and/or\r
- 'set_library_dirs()'. 'runtime_library_dirs' is a list of\r
- directories that will be embedded into the shared library and used\r
- to search for other shared libraries that *it* depends on at\r
- run-time. (This may only be relevant on Unix.)\r
-\r
- 'export_symbols' is a list of symbols that the shared library will\r
- export. (This appears to be relevant only on Windows.)\r
-\r
- 'debug' is as for 'compile()' and 'create_static_lib()', with the\r
- slight distinction that it actually matters on most platforms (as\r
- opposed to 'create_static_lib()', which includes a 'debug' flag\r
- mostly for form's sake).\r
-\r
- 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except\r
- of course that they supply command-line arguments for the\r
- particular linker being used).\r
-\r
- 'target_lang' is the target language for which the given objects\r
- are being compiled. This allows specific linkage time treatment of\r
- certain languages.\r
-\r
- Raises LinkError on failure.\r
- """\r
- raise NotImplementedError\r
-\r
-\r
- # Old 'link_*()' methods, rewritten to use the new 'link()' method.\r
-\r
- def link_shared_lib(self, objects, output_libname, output_dir=None,\r
- libraries=None, library_dirs=None,\r
- runtime_library_dirs=None, export_symbols=None,\r
- debug=0, extra_preargs=None, extra_postargs=None,\r
- build_temp=None, target_lang=None):\r
- self.link(CCompiler.SHARED_LIBRARY, objects,\r
- self.library_filename(output_libname, lib_type='shared'),\r
- output_dir,\r
- libraries, library_dirs, runtime_library_dirs,\r
- export_symbols, debug,\r
- extra_preargs, extra_postargs, build_temp, target_lang)\r
-\r
-\r
- def link_shared_object(self, objects, output_filename, output_dir=None,\r
- libraries=None, library_dirs=None,\r
- runtime_library_dirs=None, export_symbols=None,\r
- debug=0, extra_preargs=None, extra_postargs=None,\r
- build_temp=None, target_lang=None):\r
- self.link(CCompiler.SHARED_OBJECT, objects,\r
- output_filename, output_dir,\r
- libraries, library_dirs, runtime_library_dirs,\r
- export_symbols, debug,\r
- extra_preargs, extra_postargs, build_temp, target_lang)\r
-\r
- def link_executable(self, objects, output_progname, output_dir=None,\r
- libraries=None, library_dirs=None,\r
- runtime_library_dirs=None, debug=0, extra_preargs=None,\r
- extra_postargs=None, target_lang=None):\r
- self.link(CCompiler.EXECUTABLE, objects,\r
- self.executable_filename(output_progname), output_dir,\r
- libraries, library_dirs, runtime_library_dirs, None,\r
- debug, extra_preargs, extra_postargs, None, target_lang)\r
-\r
-\r
- # -- Miscellaneous methods -----------------------------------------\r
- # These are all used by the 'gen_lib_options() function; there is\r
- # no appropriate default implementation so subclasses should\r
- # implement all of these.\r
-\r
- def library_dir_option(self, dir):\r
- """Return the compiler option to add 'dir' to the list of\r
- directories searched for libraries.\r
- """\r
- raise NotImplementedError\r
-\r
- def runtime_library_dir_option(self, dir):\r
- """Return the compiler option to add 'dir' to the list of\r
- directories searched for runtime libraries.\r
- """\r
- raise NotImplementedError\r
-\r
- def library_option(self, lib):\r
- """Return the compiler option to add 'dir' to the list of libraries\r
- linked into the shared library or executable.\r
- """\r
- raise NotImplementedError\r
-\r
- def has_function(self, funcname, includes=None, include_dirs=None,\r
- libraries=None, library_dirs=None):\r
- """Return a boolean indicating whether funcname is supported on\r
- the current platform. The optional arguments can be used to\r
- augment the compilation environment.\r
- """\r
-\r
- # this can't be included at module scope because it tries to\r
- # import math which might not be available at that point - maybe\r
- # the necessary logic should just be inlined?\r
- import tempfile\r
- if includes is None:\r
- includes = []\r
- if include_dirs is None:\r
- include_dirs = []\r
- if libraries is None:\r
- libraries = []\r
- if library_dirs is None:\r
- library_dirs = []\r
- fd, fname = tempfile.mkstemp(".c", funcname, text=True)\r
- f = os.fdopen(fd, "w")\r
- try:\r
- for incl in includes:\r
- f.write("""#include "%s"\n""" % incl)\r
- f.write("""\\r
-main (int argc, char **argv) {\r
- %s();\r
-}\r
-""" % funcname)\r
- finally:\r
- f.close()\r
- try:\r
- objects = self.compile([fname], include_dirs=include_dirs)\r
- except CompileError:\r
- return False\r
-\r
- try:\r
- self.link_executable(objects, "a.out",\r
- libraries=libraries,\r
- library_dirs=library_dirs)\r
- except (LinkError, TypeError):\r
- return False\r
- return True\r
-\r
- def find_library_file (self, dirs, lib, debug=0):\r
- """Search the specified list of directories for a static or shared\r
- library file 'lib' and return the full path to that file. If\r
- 'debug' true, look for a debugging version (if that makes sense on\r
- the current platform). Return None if 'lib' wasn't found in any of\r
- the specified directories.\r
- """\r
- raise NotImplementedError\r
-\r
- # -- Filename generation methods -----------------------------------\r
-\r
- # The default implementation of the filename generating methods are\r
- # prejudiced towards the Unix/DOS/Windows view of the world:\r
- # * object files are named by replacing the source file extension\r
- # (eg. .c/.cpp -> .o/.obj)\r
- # * library files (shared or static) are named by plugging the\r
- # library name and extension into a format string, eg.\r
- # "lib%s.%s" % (lib_name, ".a") for Unix static libraries\r
- # * executables are named by appending an extension (possibly\r
- # empty) to the program name: eg. progname + ".exe" for\r
- # Windows\r
- #\r
- # To reduce redundant code, these methods expect to find\r
- # several attributes in the current object (presumably defined\r
- # as class attributes):\r
- # * src_extensions -\r
- # list of C/C++ source file extensions, eg. ['.c', '.cpp']\r
- # * obj_extension -\r
- # object file extension, eg. '.o' or '.obj'\r
- # * static_lib_extension -\r
- # extension for static library files, eg. '.a' or '.lib'\r
- # * shared_lib_extension -\r
- # extension for shared library/object files, eg. '.so', '.dll'\r
- # * static_lib_format -\r
- # format string for generating static library filenames,\r
- # eg. 'lib%s.%s' or '%s.%s'\r
- # * shared_lib_format\r
- # format string for generating shared library filenames\r
- # (probably same as static_lib_format, since the extension\r
- # is one of the intended parameters to the format string)\r
- # * exe_extension -\r
- # extension for executable files, eg. '' or '.exe'\r
-\r
- def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):\r
- if output_dir is None:\r
- output_dir = ''\r
- obj_names = []\r
- for src_name in source_filenames:\r
- base, ext = os.path.splitext(src_name)\r
- base = os.path.splitdrive(base)[1] # Chop off the drive\r
- base = base[os.path.isabs(base):] # If abs, chop off leading /\r
- if ext not in self.src_extensions:\r
- raise UnknownFileError, \\r
- "unknown file type '%s' (from '%s')" % (ext, src_name)\r
- if strip_dir:\r
- base = os.path.basename(base)\r
- obj_names.append(os.path.join(output_dir,\r
- base + self.obj_extension))\r
- return obj_names\r
-\r
- def shared_object_filename(self, basename, strip_dir=0, output_dir=''):\r
- assert output_dir is not None\r
- if strip_dir:\r
- basename = os.path.basename (basename)\r
- return os.path.join(output_dir, basename + self.shared_lib_extension)\r
-\r
- def executable_filename(self, basename, strip_dir=0, output_dir=''):\r
- assert output_dir is not None\r
- if strip_dir:\r
- basename = os.path.basename (basename)\r
- return os.path.join(output_dir, basename + (self.exe_extension or ''))\r
-\r
- def library_filename(self, libname, lib_type='static', # or 'shared'\r
- strip_dir=0, output_dir=''):\r
- assert output_dir is not None\r
- if lib_type not in ("static", "shared", "dylib"):\r
- raise ValueError, "'lib_type' must be \"static\", \"shared\" or \"dylib\""\r
- fmt = getattr(self, lib_type + "_lib_format")\r
- ext = getattr(self, lib_type + "_lib_extension")\r
-\r
- dir, base = os.path.split (libname)\r
- filename = fmt % (base, ext)\r
- if strip_dir:\r
- dir = ''\r
-\r
- return os.path.join(output_dir, dir, filename)\r
-\r
-\r
- # -- Utility methods -----------------------------------------------\r
-\r
- def announce(self, msg, level=1):\r
- log.debug(msg)\r
-\r
- def debug_print(self, msg):\r
- from distutils.debug import DEBUG\r
- if DEBUG:\r
- print msg\r
-\r
- def warn(self, msg):\r
- sys.stderr.write("warning: %s\n" % msg)\r
-\r
- def execute(self, func, args, msg=None, level=1):\r
- execute(func, args, msg, self.dry_run)\r
-\r
- def spawn(self, cmd):\r
- spawn(cmd, dry_run=self.dry_run)\r
-\r
- def move_file(self, src, dst):\r
- return move_file(src, dst, dry_run=self.dry_run)\r
-\r
- def mkpath(self, name, mode=0777):\r
- mkpath(name, mode, dry_run=self.dry_run)\r
-\r
-\r
-# class CCompiler\r
-\r
-\r
-# Map a sys.platform/os.name ('posix', 'nt') to the default compiler\r
-# type for that platform. Keys are interpreted as re match\r
-# patterns. Order is important; platform mappings are preferred over\r
-# OS names.\r
-_default_compilers = (\r
-\r
- # Platform string mappings\r
-\r
- # on a cygwin built python we can use gcc like an ordinary UNIXish\r
- # compiler\r
- ('cygwin.*', 'unix'),\r
- ('os2emx', 'emx'),\r
-\r
- # OS name mappings\r
- ('posix', 'unix'),\r
- ('nt', 'msvc'),\r
-\r
- )\r
-\r
-def get_default_compiler(osname=None, platform=None):\r
- """ Determine the default compiler to use for the given platform.\r
-\r
- osname should be one of the standard Python OS names (i.e. the\r
- ones returned by os.name) and platform the common value\r
- returned by sys.platform for the platform in question.\r
-\r
- The default values are os.name and sys.platform in case the\r
- parameters are not given.\r
-\r
- """\r
- if osname is None:\r
- osname = os.name\r
- if platform is None:\r
- platform = sys.platform\r
- for pattern, compiler in _default_compilers:\r
- if re.match(pattern, platform) is not None or \\r
- re.match(pattern, osname) is not None:\r
- return compiler\r
- # Default to Unix compiler\r
- return 'unix'\r
-\r
-# Map compiler types to (module_name, class_name) pairs -- ie. where to\r
-# find the code that implements an interface to this compiler. (The module\r
-# is assumed to be in the 'distutils' package.)\r
-compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler',\r
- "standard UNIX-style compiler"),\r
- 'msvc': ('msvccompiler', 'MSVCCompiler',\r
- "Microsoft Visual C++"),\r
- 'cygwin': ('cygwinccompiler', 'CygwinCCompiler',\r
- "Cygwin port of GNU C Compiler for Win32"),\r
- 'mingw32': ('cygwinccompiler', 'Mingw32CCompiler',\r
- "Mingw32 port of GNU C Compiler for Win32"),\r
- 'bcpp': ('bcppcompiler', 'BCPPCompiler',\r
- "Borland C++ Compiler"),\r
- 'emx': ('emxccompiler', 'EMXCCompiler',\r
- "EMX port of GNU C Compiler for OS/2"),\r
- }\r
-\r
-def show_compilers():\r
- """Print list of available compilers (used by the "--help-compiler"\r
- options to "build", "build_ext", "build_clib").\r
- """\r
- # XXX this "knows" that the compiler option it's describing is\r
- # "--compiler", which just happens to be the case for the three\r
- # commands that use it.\r
- from distutils.fancy_getopt import FancyGetopt\r
- compilers = []\r
- for compiler in compiler_class.keys():\r
- compilers.append(("compiler="+compiler, None,\r
- compiler_class[compiler][2]))\r
- compilers.sort()\r
- pretty_printer = FancyGetopt(compilers)\r
- pretty_printer.print_help("List of available compilers:")\r
-\r
-\r
-def new_compiler(plat=None, compiler=None, verbose=0, dry_run=0, force=0):\r
- """Generate an instance of some CCompiler subclass for the supplied\r
- platform/compiler combination. 'plat' defaults to 'os.name'\r
- (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler\r
- for that platform. Currently only 'posix' and 'nt' are supported, and\r
- the default compilers are "traditional Unix interface" (UnixCCompiler\r
- class) and Visual C++ (MSVCCompiler class). Note that it's perfectly\r
- possible to ask for a Unix compiler object under Windows, and a\r
- Microsoft compiler object under Unix -- if you supply a value for\r
- 'compiler', 'plat' is ignored.\r
- """\r
- if plat is None:\r
- plat = os.name\r
-\r
- try:\r
- if compiler is None:\r
- compiler = get_default_compiler(plat)\r
-\r
- (module_name, class_name, long_description) = compiler_class[compiler]\r
- except KeyError:\r
- msg = "don't know how to compile C/C++ code on platform '%s'" % plat\r
- if compiler is not None:\r
- msg = msg + " with '%s' compiler" % compiler\r
- raise DistutilsPlatformError, msg\r
-\r
- try:\r
- module_name = "distutils." + module_name\r
- __import__ (module_name)\r
- module = sys.modules[module_name]\r
- klass = vars(module)[class_name]\r
- except ImportError:\r
- raise DistutilsModuleError, \\r
- "can't compile C/C++ code: unable to load module '%s'" % \\r
- module_name\r
- except KeyError:\r
- raise DistutilsModuleError, \\r
- ("can't compile C/C++ code: unable to find class '%s' " +\r
- "in module '%s'") % (class_name, module_name)\r
-\r
- # XXX The None is necessary to preserve backwards compatibility\r
- # with classes that expect verbose to be the first positional\r
- # argument.\r
- return klass(None, dry_run, force)\r
-\r
-\r
-def gen_preprocess_options(macros, include_dirs):\r
- """Generate C pre-processor options (-D, -U, -I) as used by at least\r
- two types of compilers: the typical Unix compiler and Visual C++.\r
- 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)\r
- means undefine (-U) macro 'name', and (name,value) means define (-D)\r
- macro 'name' to 'value'. 'include_dirs' is just a list of directory\r
- names to be added to the header file search path (-I). Returns a list\r
- of command-line options suitable for either Unix compilers or Visual\r
- C++.\r
- """\r
- # XXX it would be nice (mainly aesthetic, and so we don't generate\r
- # stupid-looking command lines) to go over 'macros' and eliminate\r
- # redundant definitions/undefinitions (ie. ensure that only the\r
- # latest mention of a particular macro winds up on the command\r
- # line). I don't think it's essential, though, since most (all?)\r
- # Unix C compilers only pay attention to the latest -D or -U\r
- # mention of a macro on their command line. Similar situation for\r
- # 'include_dirs'. I'm punting on both for now. Anyways, weeding out\r
- # redundancies like this should probably be the province of\r
- # CCompiler, since the data structures used are inherited from it\r
- # and therefore common to all CCompiler classes.\r
-\r
- pp_opts = []\r
- for macro in macros:\r
-\r
- if not (isinstance(macro, tuple) and\r
- 1 <= len (macro) <= 2):\r
- raise TypeError, \\r
- ("bad macro definition '%s': " +\r
- "each element of 'macros' list must be a 1- or 2-tuple") % \\r
- macro\r
-\r
- if len (macro) == 1: # undefine this macro\r
- pp_opts.append ("-U%s" % macro[0])\r
- elif len (macro) == 2:\r
- if macro[1] is None: # define with no explicit value\r
- pp_opts.append ("-D%s" % macro[0])\r
- else:\r
- # XXX *don't* need to be clever about quoting the\r
- # macro value here, because we're going to avoid the\r
- # shell at all costs when we spawn the command!\r
- pp_opts.append ("-D%s=%s" % macro)\r
-\r
- for dir in include_dirs:\r
- pp_opts.append ("-I%s" % dir)\r
-\r
- return pp_opts\r
-\r
-\r
-def gen_lib_options(compiler, library_dirs, runtime_library_dirs, libraries):\r
- """Generate linker options for searching library directories and\r
- linking with specific libraries.\r
-\r
- 'libraries' and 'library_dirs' are, respectively, lists of library names\r
- (not filenames!) and search directories. Returns a list of command-line\r
- options suitable for use with some compiler (depending on the two format\r
- strings passed in).\r
- """\r
- lib_opts = []\r
-\r
- for dir in library_dirs:\r
- lib_opts.append(compiler.library_dir_option(dir))\r
-\r
- for dir in runtime_library_dirs:\r
- opt = compiler.runtime_library_dir_option(dir)\r
- if isinstance(opt, list):\r
- lib_opts.extend(opt)\r
- else:\r
- lib_opts.append(opt)\r
-\r
- # XXX it's important that we *not* remove redundant library mentions!\r
- # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to\r
- # resolve all symbols. I just hope we never have to say "-lfoo obj.o\r
- # -lbar" to get things to work -- that's certainly a possibility, but a\r
- # pretty nasty way to arrange your C code.\r
-\r
- for lib in libraries:\r
- lib_dir, lib_name = os.path.split(lib)\r
- if lib_dir != '':\r
- lib_file = compiler.find_library_file([lib_dir], lib_name)\r
- if lib_file is not None:\r
- lib_opts.append(lib_file)\r
- else:\r
- compiler.warn("no library file corresponding to "\r
- "'%s' found (skipping)" % lib)\r
- else:\r
- lib_opts.append(compiler.library_option(lib))\r
-\r
- return lib_opts\r