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