blob: f1a50cbddcf79432c9ae39d0d7dbf8460ff37b18 [file] [log] [blame]
Greg Ward3f81cf71999-07-10 02:03:53 +00001"""distutils.ccompiler
2
3Contains CCompiler, an abstract base class that defines the interface
4for the Distutils compiler abstraction model."""
5
6# created 1999/07/05, Greg Ward
7
Greg Ward3ce77fd2000-03-02 01:49:45 +00008__revision__ = "$Id$"
Greg Ward3f81cf71999-07-10 02:03:53 +00009
Marc-André Lemburg636b9062001-02-19 09:20:04 +000010import sys, os, re
Greg Ward3f81cf71999-07-10 02:03:53 +000011from types import *
12from copy import copy
13from distutils.errors import *
Greg Warde1aaaa61999-08-14 23:50:50 +000014from distutils.spawn import spawn
Greg Warde5c62bf2000-06-25 02:08:18 +000015from distutils.file_util import move_file
16from distutils.dir_util import mkpath
17from distutils.dep_util import newer_pairwise, newer_group
Greg Ward9dddbb42000-08-02 01:38:20 +000018from distutils.util import split_quoted, execute
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +000019from distutils import log
Greg Ward3f81cf71999-07-10 02:03:53 +000020
21class CCompiler:
22 """Abstract base class to define the interface that must be implemented
Greg Wardc3a43b42000-06-24 18:10:48 +000023 by real compiler classes. Also has some utility methods used by
24 several compiler classes.
Greg Ward3f81cf71999-07-10 02:03:53 +000025
Greg Wardc3a43b42000-06-24 18:10:48 +000026 The basic idea behind a compiler abstraction class is that each
27 instance can be used for all the compile/link steps in building a
28 single project. Thus, attributes common to all of those compile and
29 link steps -- include directories, macros to define, libraries to link
30 against, etc. -- are attributes of the compiler instance. To allow for
31 variability in how individual files are treated, most of those
32 attributes may be varied on a per-compilation or per-link basis.
33 """
Greg Ward3f81cf71999-07-10 02:03:53 +000034
Greg Ward802d6b71999-09-29 12:20:55 +000035 # 'compiler_type' is a class attribute that identifies this class. It
36 # keeps code that wants to know what kind of compiler it's dealing with
37 # from having to import all possible compiler classes just to do an
38 # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type'
39 # should really, really be one of the keys of the 'compiler_class'
40 # dictionary (see below -- used by the 'new_compiler()' factory
41 # function) -- authors of new compiler interface classes are
42 # responsible for updating 'compiler_class'!
43 compiler_type = None
Greg Ward3f81cf71999-07-10 02:03:53 +000044
45 # XXX things not handled by this compiler abstraction model:
46 # * client can't provide additional options for a compiler,
47 # e.g. warning, optimization, debugging flags. Perhaps this
48 # should be the domain of concrete compiler abstraction classes
49 # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
50 # class should have methods for the common ones.
Greg Ward3f81cf71999-07-10 02:03:53 +000051 # * can't completely override the include or library searchg
52 # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
Greg Warde1aaaa61999-08-14 23:50:50 +000053 # I'm not sure how widely supported this is even by Unix
Greg Ward3f81cf71999-07-10 02:03:53 +000054 # compilers, much less on other platforms. And I'm even less
Greg Warde1aaaa61999-08-14 23:50:50 +000055 # sure how useful it is; maybe for cross-compiling, but
56 # support for that is a ways off. (And anyways, cross
57 # compilers probably have a dedicated binary with the
58 # right paths compiled in. I hope.)
Greg Ward3f81cf71999-07-10 02:03:53 +000059 # * can't do really freaky things with the library list/library
60 # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
61 # different versions of libfoo.a in different locations. I
62 # think this is useless without the ability to null out the
63 # library search path anyways.
Fred Drakeb94b8492001-12-06 20:51:35 +000064
Greg Ward3f81cf71999-07-10 02:03:53 +000065
Greg Ward32c4a8a2000-03-06 03:40:29 +000066 # Subclasses that rely on the standard filename generation methods
67 # implemented below should override these; see the comment near
68 # those methods ('object_filenames()' et. al.) for details:
69 src_extensions = None # list of strings
70 obj_extension = None # string
71 static_lib_extension = None
72 shared_lib_extension = None # string
73 static_lib_format = None # format string
74 shared_lib_format = None # prob. same as static_lib_format
75 exe_extension = None # string
76
77
Greg Warde1aaaa61999-08-14 23:50:50 +000078 def __init__ (self,
79 verbose=0,
Greg Ward3febd601999-10-03 20:41:02 +000080 dry_run=0,
81 force=0):
Greg Warde1aaaa61999-08-14 23:50:50 +000082
Greg Warde1aaaa61999-08-14 23:50:50 +000083 self.dry_run = dry_run
Greg Ward3febd601999-10-03 20:41:02 +000084 self.force = force
Greg Ward3f81cf71999-07-10 02:03:53 +000085
Greg Ward9b17cb51999-09-13 03:07:24 +000086 # 'output_dir': a common output directory for object, library,
87 # shared object, and shared library files
88 self.output_dir = None
89
Greg Ward3f81cf71999-07-10 02:03:53 +000090 # 'macros': a list of macro definitions (or undefinitions). A
91 # macro definition is a 2-tuple (name, value), where the value is
92 # either a string or None (no explicit value). A macro
93 # undefinition is a 1-tuple (name,).
94 self.macros = []
95
Greg Ward3f81cf71999-07-10 02:03:53 +000096 # 'include_dirs': a list of directories to search for include files
97 self.include_dirs = []
98
99 # 'libraries': a list of libraries to include in any link
100 # (library names, not filenames: eg. "foo" not "libfoo.a")
101 self.libraries = []
102
103 # 'library_dirs': a list of directories to search for libraries
104 self.library_dirs = []
105
Greg Warde1aaaa61999-08-14 23:50:50 +0000106 # 'runtime_library_dirs': a list of directories to search for
107 # shared libraries/objects at runtime
108 self.runtime_library_dirs = []
109
Greg Ward3f81cf71999-07-10 02:03:53 +0000110 # 'objects': a list of object files (or similar, such as explicitly
111 # named library files) to include on any link
112 self.objects = []
113
Greg Warde5c62bf2000-06-25 02:08:18 +0000114 for key in self.executables.keys():
115 self.set_executable(key, self.executables[key])
116
Greg Ward3f81cf71999-07-10 02:03:53 +0000117 # __init__ ()
118
119
Greg Warde5c62bf2000-06-25 02:08:18 +0000120 def set_executables (self, **args):
121
122 """Define the executables (and options for them) that will be run
123 to perform the various stages of compilation. The exact set of
124 executables that may be specified here depends on the compiler
125 class (via the 'executables' class attribute), but most will have:
126 compiler the C/C++ compiler
127 linker_so linker used to create shared objects and libraries
128 linker_exe linker used to create binary executables
129 archiver static library creator
130
131 On platforms with a command-line (Unix, DOS/Windows), each of these
132 is a string that will be split into executable name and (optional)
133 list of arguments. (Splitting the string is done similarly to how
134 Unix shells operate: words are delimited by spaces, but quotes and
135 backslashes can override this. See
136 'distutils.util.split_quoted()'.)
137 """
138
139 # Note that some CCompiler implementation classes will define class
140 # attributes 'cpp', 'cc', etc. with hard-coded executable names;
141 # this is appropriate when a compiler class is for exactly one
142 # compiler/OS combination (eg. MSVCCompiler). Other compiler
143 # classes (UnixCCompiler, in particular) are driven by information
144 # discovered at run-time, since there are many different ways to do
145 # basically the same things with Unix C compilers.
146
147 for key in args.keys():
148 if not self.executables.has_key(key):
149 raise ValueError, \
150 "unknown executable '%s' for class %s" % \
151 (key, self.__class__.__name__)
152 self.set_executable(key, args[key])
153
154 # set_executables ()
155
156 def set_executable(self, key, value):
157 if type(value) is StringType:
158 setattr(self, key, split_quoted(value))
159 else:
160 setattr(self, key, value)
Fred Drakeb94b8492001-12-06 20:51:35 +0000161
Greg Warde5c62bf2000-06-25 02:08:18 +0000162
Greg Ward3f81cf71999-07-10 02:03:53 +0000163 def _find_macro (self, name):
164 i = 0
165 for defn in self.macros:
166 if defn[0] == name:
167 return i
168 i = i + 1
169
170 return None
171
172
173 def _check_macro_definitions (self, definitions):
174 """Ensures that every element of 'definitions' is a valid macro
Greg Wardc3a43b42000-06-24 18:10:48 +0000175 definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do
176 nothing if all definitions are OK, raise TypeError otherwise.
177 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000178 for defn in definitions:
179 if not (type (defn) is TupleType and
180 (len (defn) == 1 or
181 (len (defn) == 2 and
182 (type (defn[1]) is StringType or defn[1] is None))) and
183 type (defn[0]) is StringType):
184 raise TypeError, \
185 ("invalid macro definition '%s': " % defn) + \
186 "must be tuple (string,), (string, string), or " + \
187 "(string, None)"
188
189
190 # -- Bookkeeping methods -------------------------------------------
191
192 def define_macro (self, name, value=None):
Greg Wardc3a43b42000-06-24 18:10:48 +0000193 """Define a preprocessor macro for all compilations driven by this
194 compiler object. The optional parameter 'value' should be a
195 string; if it is not supplied, then the macro will be defined
196 without an explicit value and the exact outcome depends on the
197 compiler used (XXX true? does ANSI say anything about this?)
198 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000199 # Delete from the list of macro definitions/undefinitions if
200 # already there (so that this one will take precedence).
201 i = self._find_macro (name)
202 if i is not None:
203 del self.macros[i]
204
205 defn = (name, value)
206 self.macros.append (defn)
207
208
209 def undefine_macro (self, name):
210 """Undefine a preprocessor macro for all compilations driven by
Greg Wardc3a43b42000-06-24 18:10:48 +0000211 this compiler object. If the same macro is defined by
212 'define_macro()' and undefined by 'undefine_macro()' the last call
213 takes precedence (including multiple redefinitions or
214 undefinitions). If the macro is redefined/undefined on a
215 per-compilation basis (ie. in the call to 'compile()'), then that
216 takes precedence.
217 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000218 # Delete from the list of macro definitions/undefinitions if
219 # already there (so that this one will take precedence).
220 i = self._find_macro (name)
221 if i is not None:
222 del self.macros[i]
223
224 undefn = (name,)
225 self.macros.append (undefn)
226
227
228 def add_include_dir (self, dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000229 """Add 'dir' to the list of directories that will be searched for
230 header files. The compiler is instructed to search directories in
231 the order in which they are supplied by successive calls to
232 'add_include_dir()'.
233 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000234 self.include_dirs.append (dir)
235
236 def set_include_dirs (self, dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000237 """Set the list of directories that will be searched to 'dirs' (a
238 list of strings). Overrides any preceding calls to
239 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
240 to the list passed to 'set_include_dirs()'. This does not affect
241 any list of standard include directories that the compiler may
242 search by default.
243 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000244 self.include_dirs = copy (dirs)
245
246
247 def add_library (self, libname):
Greg Wardc3a43b42000-06-24 18:10:48 +0000248 """Add 'libname' to the list of libraries that will be included in
249 all links driven by this compiler object. Note that 'libname'
250 should *not* be the name of a file containing a library, but the
251 name of the library itself: the actual filename will be inferred by
252 the linker, the compiler, or the compiler class (depending on the
253 platform).
Greg Ward3f81cf71999-07-10 02:03:53 +0000254
Greg Wardc3a43b42000-06-24 18:10:48 +0000255 The linker will be instructed to link against libraries in the
256 order they were supplied to 'add_library()' and/or
257 'set_libraries()'. It is perfectly valid to duplicate library
258 names; the linker will be instructed to link against libraries as
259 many times as they are mentioned.
260 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000261 self.libraries.append (libname)
262
263 def set_libraries (self, libnames):
Greg Wardc3a43b42000-06-24 18:10:48 +0000264 """Set the list of libraries to be included in all links driven by
265 this compiler object to 'libnames' (a list of strings). This does
266 not affect any standard system libraries that the linker may
267 include by default.
268 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000269 self.libraries = copy (libnames)
270
271
272 def add_library_dir (self, dir):
273 """Add 'dir' to the list of directories that will be searched for
Greg Wardc3a43b42000-06-24 18:10:48 +0000274 libraries specified to 'add_library()' and 'set_libraries()'. The
275 linker will be instructed to search for libraries in the order they
276 are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
277 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000278 self.library_dirs.append (dir)
279
280 def set_library_dirs (self, dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000281 """Set the list of library search directories to 'dirs' (a list of
282 strings). This does not affect any standard library search path
283 that the linker may search by default.
284 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000285 self.library_dirs = copy (dirs)
286
287
Greg Warde1aaaa61999-08-14 23:50:50 +0000288 def add_runtime_library_dir (self, dir):
289 """Add 'dir' to the list of directories that will be searched for
Greg Wardc3a43b42000-06-24 18:10:48 +0000290 shared libraries at runtime.
291 """
Greg Warde1aaaa61999-08-14 23:50:50 +0000292 self.runtime_library_dirs.append (dir)
293
294 def set_runtime_library_dirs (self, dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000295 """Set the list of directories to search for shared libraries at
296 runtime to 'dirs' (a list of strings). This does not affect any
297 standard search path that the runtime linker may search by
298 default.
299 """
Greg Warde1aaaa61999-08-14 23:50:50 +0000300 self.runtime_library_dirs = copy (dirs)
301
302
Greg Ward3f81cf71999-07-10 02:03:53 +0000303 def add_link_object (self, object):
Greg Wardc3a43b42000-06-24 18:10:48 +0000304 """Add 'object' to the list of object files (or analogues, such as
Greg Ward612eb9f2000-07-27 02:13:20 +0000305 explicitly named library files or the output of "resource
Greg Wardc3a43b42000-06-24 18:10:48 +0000306 compilers") to be included in every link driven by this compiler
307 object.
308 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000309 self.objects.append (object)
310
311 def set_link_objects (self, objects):
Greg Wardc3a43b42000-06-24 18:10:48 +0000312 """Set the list of object files (or analogues) to be included in
313 every link to 'objects'. This does not affect any standard object
314 files that the linker may include by default (such as system
315 libraries).
316 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000317 self.objects = copy (objects)
318
319
Thomas Hellere6500802002-04-25 17:03:30 +0000320 # -- Private utility methods --------------------------------------
Greg Ward32c4a8a2000-03-06 03:40:29 +0000321 # (here for the convenience of subclasses)
322
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000323 # Helper method to prep compiler in subclass compile() methods
324
325 def _setup_compile(self, outdir, macros, incdirs, sources, depends,
326 extra):
327 """Process arguments and decide which source files to compile.
328
329 Merges _fix_compile_args() and _prep_compile().
330 """
331 if outdir is None:
332 outdir = self.output_dir
333 elif type(outdir) is not StringType:
334 raise TypeError, "'output_dir' must be a string or None"
335
336 if macros is None:
337 macros = self.macros
338 elif type(macros) is ListType:
339 macros = macros + (self.macros or [])
340 else:
341 raise TypeError, "'macros' (if supplied) must be a list of tuples"
342
343 if incdirs is None:
344 incdirs = self.include_dirs
345 elif type(incdirs) in (ListType, TupleType):
346 incdirs = list(incdirs) + (self.include_dirs or [])
347 else:
348 raise TypeError, \
349 "'include_dirs' (if supplied) must be a list of strings"
350
351 if extra is None:
352 extra = []
353
354 # Get the list of expected output (object) files
355 objects = self.object_filenames(sources, 1, outdir)
356 assert len(objects) == len(sources)
357
358 # XXX should redo this code to eliminate skip_source entirely.
359 # XXX instead create build and issue skip messages inline
360
361 if self.force:
362 skip_source = {} # rebuild everything
363 for source in sources:
364 skip_source[source] = 0
365 elif depends is None:
366 # If depends is None, figure out which source files we
367 # have to recompile according to a simplistic check. We
368 # just compare the source and object file, no deep
369 # dependency checking involving header files.
370 skip_source = {} # rebuild everything
371 for source in sources: # no wait, rebuild nothing
372 skip_source[source] = 1
373
374 n_sources, n_objects = newer_pairwise(sources, objects)
375 for source in n_sources: # no really, only rebuild what's
376 skip_source[source] = 0 # out-of-date
377 else:
378 # If depends is a list of files, then do a different
379 # simplistic check. Assume that each object depends on
380 # its source and all files in the depends list.
381 skip_source = {}
382 # L contains all the depends plus a spot at the end for a
383 # particular source file
384 L = depends[:] + [None]
385 for i in range(len(objects)):
386 source = sources[i]
387 L[-1] = source
388 if newer_group(L, objects[i]):
389 skip_source[source] = 0
390 else:
391 skip_source[source] = 1
392
393 pp_opts = gen_preprocess_options(macros, incdirs)
394
395 build = {}
396 for i in range(len(sources)):
397 src = sources[i]
398 obj = objects[i]
399 ext = os.path.splitext(src)[1]
400 self.mkpath(os.path.dirname(obj))
401 if skip_source[src]:
402 log.debug("skipping %s (%s up-to-date)", src, obj)
403 else:
404 build[obj] = src, ext
405
406 return macros, objects, extra, pp_opts, build
407
408 def _get_cc_args(self, pp_opts, debug, before):
409 # works for unixccompiler, emxccompiler, cygwinccompiler
410 cc_args = pp_opts + ['-c']
411 if debug:
412 cc_args[:0] = ['-g']
413 if before:
414 cc_args[:0] = before
415 return cc_args
416
Greg Ward32c4a8a2000-03-06 03:40:29 +0000417 def _fix_compile_args (self, output_dir, macros, include_dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000418 """Typecheck and fix-up some of the arguments to the 'compile()'
419 method, and return fixed-up values. Specifically: if 'output_dir'
420 is None, replaces it with 'self.output_dir'; ensures that 'macros'
421 is a list, and augments it with 'self.macros'; ensures that
422 'include_dirs' is a list, and augments it with 'self.include_dirs'.
423 Guarantees that the returned values are of the correct type,
424 i.e. for 'output_dir' either string or None, and for 'macros' and
425 'include_dirs' either list or None.
426 """
Greg Ward32c4a8a2000-03-06 03:40:29 +0000427 if output_dir is None:
428 output_dir = self.output_dir
429 elif type (output_dir) is not StringType:
430 raise TypeError, "'output_dir' must be a string or None"
431
432 if macros is None:
433 macros = self.macros
434 elif type (macros) is ListType:
435 macros = macros + (self.macros or [])
436 else:
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000437 raise TypeError, "'macros' (if supplied) must be a list of tuples"
Greg Ward32c4a8a2000-03-06 03:40:29 +0000438
439 if include_dirs is None:
440 include_dirs = self.include_dirs
441 elif type (include_dirs) in (ListType, TupleType):
442 include_dirs = list (include_dirs) + (self.include_dirs or [])
443 else:
444 raise TypeError, \
445 "'include_dirs' (if supplied) must be a list of strings"
Fred Drakeb94b8492001-12-06 20:51:35 +0000446
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000447 return output_dir, macros, include_dirs
Greg Ward32c4a8a2000-03-06 03:40:29 +0000448
449 # _fix_compile_args ()
450
451
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000452 def _prep_compile(self, sources, output_dir, depends=None):
453 """Decide which souce files must be recompiled.
454
455 Determine the list of object files corresponding to 'sources',
456 and figure out which ones really need to be recompiled.
457 Return a list of all object files and a dictionary telling
458 which source files can be skipped.
Greg Wardc3a43b42000-06-24 18:10:48 +0000459 """
Fred Drakeb94b8492001-12-06 20:51:35 +0000460 # Get the list of expected output (object) files
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000461 objects = self.object_filenames(sources, strip_dir=1,
462 output_dir=output_dir)
463 assert len(objects) == len(sources)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000464
465 if self.force:
466 skip_source = {} # rebuild everything
467 for source in sources:
468 skip_source[source] = 0
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000469 elif depends is None:
470 # If depends is None, figure out which source files we
471 # have to recompile according to a simplistic check. We
472 # just compare the source and object file, no deep
473 # dependency checking involving header files.
Greg Ward32c4a8a2000-03-06 03:40:29 +0000474 skip_source = {} # rebuild everything
475 for source in sources: # no wait, rebuild nothing
476 skip_source[source] = 1
477
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000478 n_sources, n_objects = newer_pairwise(sources, objects)
Greg Wardc3a43b42000-06-24 18:10:48 +0000479 for source in n_sources: # no really, only rebuild what's
480 skip_source[source] = 0 # out-of-date
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000481 else:
482 # If depends is a list of files, then do a different
483 # simplistic check. Assume that each object depends on
484 # its source and all files in the depends list.
485 skip_source = {}
486 # L contains all the depends plus a spot at the end for a
487 # particular source file
488 L = depends[:] + [None]
489 for i in range(len(objects)):
490 source = sources[i]
491 L[-1] = source
492 if newer_group(L, objects[i]):
493 skip_source[source] = 0
494 else:
495 skip_source[source] = 1
Greg Ward32c4a8a2000-03-06 03:40:29 +0000496
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000497 return objects, skip_source
Greg Ward32c4a8a2000-03-06 03:40:29 +0000498
499 # _prep_compile ()
500
501
Greg Wardf10f95d2000-03-26 21:37:09 +0000502 def _fix_object_args (self, objects, output_dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000503 """Typecheck and fix up some arguments supplied to various methods.
504 Specifically: ensure that 'objects' is a list; if output_dir is
505 None, replace with self.output_dir. Return fixed versions of
506 'objects' and 'output_dir'.
507 """
Greg Ward32c4a8a2000-03-06 03:40:29 +0000508 if type (objects) not in (ListType, TupleType):
509 raise TypeError, \
510 "'objects' must be a list or tuple of strings"
511 objects = list (objects)
Fred Drakeb94b8492001-12-06 20:51:35 +0000512
Greg Ward32c4a8a2000-03-06 03:40:29 +0000513 if output_dir is None:
514 output_dir = self.output_dir
515 elif type (output_dir) is not StringType:
516 raise TypeError, "'output_dir' must be a string or None"
517
Greg Wardf10f95d2000-03-26 21:37:09 +0000518 return (objects, output_dir)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000519
Greg Ward32c4a8a2000-03-06 03:40:29 +0000520
Greg Wardf10f95d2000-03-26 21:37:09 +0000521 def _fix_lib_args (self, libraries, library_dirs, runtime_library_dirs):
522 """Typecheck and fix up some of the arguments supplied to the
Greg Wardc3a43b42000-06-24 18:10:48 +0000523 'link_*' methods. Specifically: ensure that all arguments are
524 lists, and augment them with their permanent versions
525 (eg. 'self.libraries' augments 'libraries'). Return a tuple with
526 fixed versions of all arguments.
527 """
Greg Wardf10f95d2000-03-26 21:37:09 +0000528 if libraries is None:
529 libraries = self.libraries
530 elif type (libraries) in (ListType, TupleType):
531 libraries = list (libraries) + (self.libraries or [])
Greg Ward32c4a8a2000-03-06 03:40:29 +0000532 else:
Greg Wardf10f95d2000-03-26 21:37:09 +0000533 raise TypeError, \
534 "'libraries' (if supplied) must be a list of strings"
Greg Ward32c4a8a2000-03-06 03:40:29 +0000535
Greg Wardf10f95d2000-03-26 21:37:09 +0000536 if library_dirs is None:
537 library_dirs = self.library_dirs
538 elif type (library_dirs) in (ListType, TupleType):
539 library_dirs = list (library_dirs) + (self.library_dirs or [])
540 else:
541 raise TypeError, \
542 "'library_dirs' (if supplied) must be a list of strings"
543
544 if runtime_library_dirs is None:
545 runtime_library_dirs = self.runtime_library_dirs
546 elif type (runtime_library_dirs) in (ListType, TupleType):
547 runtime_library_dirs = (list (runtime_library_dirs) +
548 (self.runtime_library_dirs or []))
549 else:
550 raise TypeError, \
551 "'runtime_library_dirs' (if supplied) " + \
552 "must be a list of strings"
553
554 return (libraries, library_dirs, runtime_library_dirs)
555
556 # _fix_lib_args ()
Greg Ward32c4a8a2000-03-06 03:40:29 +0000557
558
559 def _need_link (self, objects, output_file):
Greg Wardc3a43b42000-06-24 18:10:48 +0000560 """Return true if we need to relink the files listed in 'objects'
561 to recreate 'output_file'.
562 """
Greg Ward32c4a8a2000-03-06 03:40:29 +0000563 if self.force:
564 return 1
565 else:
566 if self.dry_run:
567 newer = newer_group (objects, output_file, missing='newer')
568 else:
569 newer = newer_group (objects, output_file)
570 return newer
571
572 # _need_link ()
573
574
Greg Ward3f81cf71999-07-10 02:03:53 +0000575 # -- Worker methods ------------------------------------------------
576 # (must be implemented by subclasses)
577
Greg Ward3ff3b032000-06-21 02:58:46 +0000578 def preprocess (self,
579 source,
580 output_file=None,
581 macros=None,
582 include_dirs=None,
583 extra_preargs=None,
584 extra_postargs=None):
585 """Preprocess a single C/C++ source file, named in 'source'.
586 Output will be written to file named 'output_file', or stdout if
587 'output_file' not supplied. 'macros' is a list of macro
588 definitions as for 'compile()', which will augment the macros set
589 with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a
590 list of directory names that will be added to the default list.
Greg Warde5c62bf2000-06-25 02:08:18 +0000591
592 Raises PreprocessError on failure.
Greg Ward3ff3b032000-06-21 02:58:46 +0000593 """
594 pass
595
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000596 def compile(self, sources, output_dir=None, macros=None,
597 include_dirs=None, debug=0, extra_preargs=None,
598 extra_postargs=None, depends=None):
599 """Compile one or more source files.
600
601 'sources' must be a list of filenames, most likely C/C++
602 files, but in reality anything that can be handled by a
603 particular compiler and compiler class (eg. MSVCCompiler can
604 handle resource files in 'sources'). Return a list of object
605 filenames, one per source filename in 'sources'. Depending on
606 the implementation, not all source files will necessarily be
607 compiled, but all corresponding object filenames will be
608 returned.
Greg Ward32c4a8a2000-03-06 03:40:29 +0000609
Greg Wardc3a43b42000-06-24 18:10:48 +0000610 If 'output_dir' is given, object files will be put under it, while
611 retaining their original path component. That is, "foo/bar.c"
612 normally compiles to "foo/bar.o" (for a Unix implementation); if
613 'output_dir' is "build", then it would compile to
614 "build/foo/bar.o".
Greg Ward3f81cf71999-07-10 02:03:53 +0000615
Greg Wardc3a43b42000-06-24 18:10:48 +0000616 'macros', if given, must be a list of macro definitions. A macro
617 definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
618 The former defines a macro; if the value is None, the macro is
619 defined without an explicit value. The 1-tuple case undefines a
620 macro. Later definitions/redefinitions/ undefinitions take
621 precedence.
Greg Ward3f81cf71999-07-10 02:03:53 +0000622
Greg Wardc3a43b42000-06-24 18:10:48 +0000623 'include_dirs', if given, must be a list of strings, the
624 directories to add to the default include file search path for this
625 compilation only.
Greg Ward3c045a52000-02-09 02:16:14 +0000626
Greg Wardc3a43b42000-06-24 18:10:48 +0000627 'debug' is a boolean; if true, the compiler will be instructed to
628 output debug symbols in (or alongside) the object file(s).
Greg Ward802d6b71999-09-29 12:20:55 +0000629
Greg Wardc3a43b42000-06-24 18:10:48 +0000630 'extra_preargs' and 'extra_postargs' are implementation- dependent.
631 On platforms that have the notion of a command-line (e.g. Unix,
632 DOS/Windows), they are most likely lists of strings: extra
633 command-line arguments to prepand/append to the compiler command
634 line. On other platforms, consult the implementation class
635 documentation. In any event, they are intended as an escape hatch
636 for those occasions when the abstract compiler framework doesn't
637 cut the mustard.
Greg Wardd1517112000-05-30 01:56:44 +0000638
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000639 'depends', if given, is a list of filenames that all targets
640 depend on. If a source file is older than any file in
641 depends, then the source file will be recompiled. This
642 supports dependency tracking, but only at a coarse
643 granularity.
644
Greg Wardc3a43b42000-06-24 18:10:48 +0000645 Raises CompileError on failure.
646 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000647
Jeremy Hylton6e08d222002-06-18 18:42:41 +0000648 # A concrete compiler class can either override this method
649 # entirely or implement _compile().
650
651 macros, objects, extra_postargs, pp_opts, build = \
652 self._setup_compile(output_dir, macros, include_dirs, sources,
653 depends, extra_postargs)
654 cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
655
656 for obj, (src, ext) in build.items():
657 self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
658
659 # Return *all* object filenames, not just the ones we just built.
660 return objects
661
662 def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
663 """Compile 'src' to product 'obj'."""
664
665 # A concrete compiler class that does not override compile()
666 # should implement _compile().
667 pass
Greg Ward3f81cf71999-07-10 02:03:53 +0000668
Greg Ward036c8052000-03-10 01:48:32 +0000669 def create_static_lib (self,
670 objects,
671 output_libname,
672 output_dir=None,
673 debug=0):
Greg Wardc3a43b42000-06-24 18:10:48 +0000674 """Link a bunch of stuff together to create a static library file.
675 The "bunch of stuff" consists of the list of object files supplied
676 as 'objects', the extra object files supplied to
677 'add_link_object()' and/or 'set_link_objects()', the libraries
678 supplied to 'add_library()' and/or 'set_libraries()', and the
679 libraries supplied as 'libraries' (if any).
Greg Ward3f81cf71999-07-10 02:03:53 +0000680
Greg Wardc3a43b42000-06-24 18:10:48 +0000681 'output_libname' should be a library name, not a filename; the
682 filename will be inferred from the library name. 'output_dir' is
683 the directory where the library file will be put.
Greg Ward3c045a52000-02-09 02:16:14 +0000684
Greg Wardc3a43b42000-06-24 18:10:48 +0000685 'debug' is a boolean; if true, debugging information will be
686 included in the library (note that on most platforms, it is the
687 compile step where this matters: the 'debug' flag is included here
688 just for consistency).
Greg Wardd1517112000-05-30 01:56:44 +0000689
Greg Wardc3a43b42000-06-24 18:10:48 +0000690 Raises LibError on failure.
691 """
Greg Ward3c045a52000-02-09 02:16:14 +0000692 pass
Fred Drakeb94b8492001-12-06 20:51:35 +0000693
Greg Ward3c045a52000-02-09 02:16:14 +0000694
Greg Ward42406482000-09-27 02:08:14 +0000695 # values for target_desc parameter in link()
696 SHARED_OBJECT = "shared_object"
697 SHARED_LIBRARY = "shared_library"
698 EXECUTABLE = "executable"
699
700 def link (self,
701 target_desc,
702 objects,
703 output_filename,
704 output_dir=None,
705 libraries=None,
706 library_dirs=None,
707 runtime_library_dirs=None,
708 export_symbols=None,
709 debug=0,
710 extra_preargs=None,
711 extra_postargs=None,
712 build_temp=None):
713 """Link a bunch of stuff together to create an executable or
714 shared library file.
715
716 The "bunch of stuff" consists of the list of object files supplied
717 as 'objects'. 'output_filename' should be a filename. If
718 'output_dir' is supplied, 'output_filename' is relative to it
719 (i.e. 'output_filename' can provide directory components if
720 needed).
Greg Ward3febd601999-10-03 20:41:02 +0000721
Greg Wardc3a43b42000-06-24 18:10:48 +0000722 'libraries' is a list of libraries to link against. These are
723 library names, not filenames, since they're translated into
724 filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
725 on Unix and "foo.lib" on DOS/Windows). However, they can include a
726 directory component, which means the linker will look in that
727 specific directory rather than searching all the normal locations.
Greg Ward5299b6a2000-05-20 13:23:21 +0000728
Greg Wardc3a43b42000-06-24 18:10:48 +0000729 'library_dirs', if supplied, should be a list of directories to
730 search for libraries that were specified as bare library names
731 (ie. no directory component). These are on top of the system
732 default and those supplied to 'add_library_dir()' and/or
733 'set_library_dirs()'. 'runtime_library_dirs' is a list of
734 directories that will be embedded into the shared library and used
735 to search for other shared libraries that *it* depends on at
736 run-time. (This may only be relevant on Unix.)
Greg Ward802d6b71999-09-29 12:20:55 +0000737
Greg Wardc3a43b42000-06-24 18:10:48 +0000738 'export_symbols' is a list of symbols that the shared library will
739 export. (This appears to be relevant only on Windows.)
Greg Ward3c045a52000-02-09 02:16:14 +0000740
Greg Wardc3a43b42000-06-24 18:10:48 +0000741 'debug' is as for 'compile()' and 'create_static_lib()', with the
742 slight distinction that it actually matters on most platforms (as
743 opposed to 'create_static_lib()', which includes a 'debug' flag
744 mostly for form's sake).
Greg Wardd1517112000-05-30 01:56:44 +0000745
Greg Wardc3a43b42000-06-24 18:10:48 +0000746 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
747 of course that they supply command-line arguments for the
748 particular linker being used).
Greg Ward3f81cf71999-07-10 02:03:53 +0000749
Greg Wardc3a43b42000-06-24 18:10:48 +0000750 Raises LinkError on failure.
751 """
Greg Ward42406482000-09-27 02:08:14 +0000752 raise NotImplementedError
753
Fred Drakeb94b8492001-12-06 20:51:35 +0000754
Greg Ward264cf742000-09-27 02:24:21 +0000755 # Old 'link_*()' methods, rewritten to use the new 'link()' method.
Greg Ward42406482000-09-27 02:08:14 +0000756
757 def link_shared_lib (self,
758 objects,
759 output_libname,
760 output_dir=None,
761 libraries=None,
762 library_dirs=None,
763 runtime_library_dirs=None,
764 export_symbols=None,
765 debug=0,
766 extra_preargs=None,
767 extra_postargs=None,
768 build_temp=None):
Fred Drakeb94b8492001-12-06 20:51:35 +0000769 self.link(CCompiler.SHARED_LIBRARY, objects,
Greg Ward42406482000-09-27 02:08:14 +0000770 self.library_filename(output_libname, lib_type='shared'),
771 output_dir,
772 libraries, library_dirs, runtime_library_dirs,
773 export_symbols, debug,
774 extra_preargs, extra_postargs, build_temp)
Fred Drakeb94b8492001-12-06 20:51:35 +0000775
Greg Ward3f81cf71999-07-10 02:03:53 +0000776
Greg Ward3f81cf71999-07-10 02:03:53 +0000777 def link_shared_object (self,
778 objects,
779 output_filename,
Greg Ward9b17cb51999-09-13 03:07:24 +0000780 output_dir=None,
Greg Ward3f81cf71999-07-10 02:03:53 +0000781 libraries=None,
Greg Ward26e48ea1999-08-29 18:17:36 +0000782 library_dirs=None,
Greg Wardf10f95d2000-03-26 21:37:09 +0000783 runtime_library_dirs=None,
Greg Ward5299b6a2000-05-20 13:23:21 +0000784 export_symbols=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000785 debug=0,
Greg Ward802d6b71999-09-29 12:20:55 +0000786 extra_preargs=None,
Greg Wardbfc79d62000-06-28 01:29:09 +0000787 extra_postargs=None,
788 build_temp=None):
Greg Ward42406482000-09-27 02:08:14 +0000789 self.link(CCompiler.SHARED_OBJECT, objects,
790 output_filename, output_dir,
791 libraries, library_dirs, runtime_library_dirs,
792 export_symbols, debug,
793 extra_preargs, extra_postargs, build_temp)
Greg Ward3f81cf71999-07-10 02:03:53 +0000794
Greg Warde1aaaa61999-08-14 23:50:50 +0000795
Greg Ward5baf1c22000-01-09 22:41:02 +0000796 def link_executable (self,
797 objects,
798 output_progname,
799 output_dir=None,
800 libraries=None,
801 library_dirs=None,
Greg Wardf10f95d2000-03-26 21:37:09 +0000802 runtime_library_dirs=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000803 debug=0,
Greg Ward5baf1c22000-01-09 22:41:02 +0000804 extra_preargs=None,
805 extra_postargs=None):
Fred Drakeb94b8492001-12-06 20:51:35 +0000806 self.link(CCompiler.EXECUTABLE, objects,
Greg Ward264cf742000-09-27 02:24:21 +0000807 self.executable_filename(output_progname), output_dir,
Fred Drakeb94b8492001-12-06 20:51:35 +0000808 libraries, library_dirs, runtime_library_dirs, None,
Greg Ward264cf742000-09-27 02:24:21 +0000809 debug, extra_preargs, extra_postargs, None)
Greg Ward5baf1c22000-01-09 22:41:02 +0000810
811
Greg Wardf7edea72000-05-20 13:31:32 +0000812 # -- Miscellaneous methods -----------------------------------------
813 # These are all used by the 'gen_lib_options() function; there is
814 # no appropriate default implementation so subclasses should
815 # implement all of these.
816
817 def library_dir_option (self, dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000818 """Return the compiler option to add 'dir' to the list of
819 directories searched for libraries.
820 """
Greg Wardf7edea72000-05-20 13:31:32 +0000821 raise NotImplementedError
822
823 def runtime_library_dir_option (self, dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000824 """Return the compiler option to add 'dir' to the list of
825 directories searched for runtime libraries.
826 """
Greg Wardf7edea72000-05-20 13:31:32 +0000827 raise NotImplementedError
828
829 def library_option (self, lib):
830 """Return the compiler option to add 'dir' to the list of libraries
Greg Wardc3a43b42000-06-24 18:10:48 +0000831 linked into the shared library or executable.
832 """
Greg Wardf7edea72000-05-20 13:31:32 +0000833 raise NotImplementedError
834
Greg Warde5e60152000-08-04 01:28:39 +0000835 def find_library_file (self, dirs, lib, debug=0):
Greg Wardf7edea72000-05-20 13:31:32 +0000836 """Search the specified list of directories for a static or shared
Greg Warde5e60152000-08-04 01:28:39 +0000837 library file 'lib' and return the full path to that file. If
838 'debug' true, look for a debugging version (if that makes sense on
839 the current platform). Return None if 'lib' wasn't found in any of
840 the specified directories.
Greg Wardc3a43b42000-06-24 18:10:48 +0000841 """
Greg Wardf7edea72000-05-20 13:31:32 +0000842 raise NotImplementedError
843
Greg Ward32c4a8a2000-03-06 03:40:29 +0000844 # -- Filename generation methods -----------------------------------
Greg Warde1aaaa61999-08-14 23:50:50 +0000845
Greg Ward32c4a8a2000-03-06 03:40:29 +0000846 # The default implementation of the filename generating methods are
847 # prejudiced towards the Unix/DOS/Windows view of the world:
848 # * object files are named by replacing the source file extension
849 # (eg. .c/.cpp -> .o/.obj)
850 # * library files (shared or static) are named by plugging the
851 # library name and extension into a format string, eg.
852 # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
853 # * executables are named by appending an extension (possibly
854 # empty) to the program name: eg. progname + ".exe" for
855 # Windows
856 #
857 # To reduce redundant code, these methods expect to find
858 # several attributes in the current object (presumably defined
859 # as class attributes):
860 # * src_extensions -
861 # list of C/C++ source file extensions, eg. ['.c', '.cpp']
862 # * obj_extension -
863 # object file extension, eg. '.o' or '.obj'
864 # * static_lib_extension -
865 # extension for static library files, eg. '.a' or '.lib'
866 # * shared_lib_extension -
867 # extension for shared library/object files, eg. '.so', '.dll'
868 # * static_lib_format -
869 # format string for generating static library filenames,
870 # eg. 'lib%s.%s' or '%s.%s'
871 # * shared_lib_format
872 # format string for generating shared library filenames
873 # (probably same as static_lib_format, since the extension
874 # is one of the intended parameters to the format string)
875 # * exe_extension -
876 # extension for executable files, eg. '' or '.exe'
Greg Ward9b17cb51999-09-13 03:07:24 +0000877
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000878 def object_filenames(self, source_filenames, strip_dir=0, output_dir=''):
879 assert output_dir is not None
Greg Ward32c4a8a2000-03-06 03:40:29 +0000880 obj_names = []
881 for src_name in source_filenames:
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000882 base, ext = os.path.splitext(src_name)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000883 if ext not in self.src_extensions:
Greg Ward9aa668b2000-06-24 02:22:49 +0000884 raise UnknownFileError, \
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000885 "unknown file type '%s' (from '%s')" % (ext, src_name)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000886 if strip_dir:
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000887 base = os.path.basename(base)
888 obj_names.append(os.path.join(output_dir,
889 base + self.obj_extension))
Greg Ward32c4a8a2000-03-06 03:40:29 +0000890 return obj_names
Greg Warde1aaaa61999-08-14 23:50:50 +0000891
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000892 def shared_object_filename(self, basename, strip_dir=0, output_dir=''):
893 assert output_dir is not None
Greg Ward32c4a8a2000-03-06 03:40:29 +0000894 if strip_dir:
895 basename = os.path.basename (basename)
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000896 return os.path.join(output_dir, basename + self.shared_lib_extension)
Greg Warde1aaaa61999-08-14 23:50:50 +0000897
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000898 def executable_filename(self, basename, strip_dir=0, output_dir=''):
899 assert output_dir is not None
Greg Ward42406482000-09-27 02:08:14 +0000900 if strip_dir:
901 basename = os.path.basename (basename)
902 return os.path.join(output_dir, basename + (self.exe_extension or ''))
Greg Ward26e48ea1999-08-29 18:17:36 +0000903
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000904 def library_filename(self, libname, lib_type='static', # or 'shared'
905 strip_dir=0, output_dir=''):
906 assert output_dir is not None
907 if lib_type not in ("static", "shared", "dylib"):
Jack Jansene259e592001-08-27 15:08:16 +0000908 raise ValueError, "'lib_type' must be \"static\", \"shared\" or \"dylib\""
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000909 fmt = getattr(self, lib_type + "_lib_format")
910 ext = getattr(self, lib_type + "_lib_extension")
Greg Ward32c4a8a2000-03-06 03:40:29 +0000911
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000912 dir, base = os.path.split (libname)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000913 filename = fmt % (base, ext)
914 if strip_dir:
915 dir = ''
916
Jeremy Hylton59b103c2002-06-13 17:26:30 +0000917 return os.path.join(output_dir, dir, filename)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000918
Greg Warde1aaaa61999-08-14 23:50:50 +0000919
920 # -- Utility methods -----------------------------------------------
921
Greg Ward9b17cb51999-09-13 03:07:24 +0000922 def announce (self, msg, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000923 log.debug(msg)
Greg Ward9b17cb51999-09-13 03:07:24 +0000924
Greg Wardf813e592000-08-04 01:31:13 +0000925 def debug_print (self, msg):
926 from distutils.core import DEBUG
927 if DEBUG:
928 print msg
929
Greg Ward3febd601999-10-03 20:41:02 +0000930 def warn (self, msg):
931 sys.stderr.write ("warning: %s\n" % msg)
932
Greg Ward9dddbb42000-08-02 01:38:20 +0000933 def execute (self, func, args, msg=None, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000934 execute(func, args, msg, self.dry_run)
Greg Ward9dddbb42000-08-02 01:38:20 +0000935
Greg Warde1aaaa61999-08-14 23:50:50 +0000936 def spawn (self, cmd):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000937 spawn (cmd, dry_run=self.dry_run)
Greg Warde1aaaa61999-08-14 23:50:50 +0000938
Greg Ward9b17cb51999-09-13 03:07:24 +0000939 def move_file (self, src, dst):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000940 return move_file (src, dst, dry_run=self.dry_run)
Greg Ward9b17cb51999-09-13 03:07:24 +0000941
Greg Ward013f0c82000-03-01 14:43:12 +0000942 def mkpath (self, name, mode=0777):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000943 mkpath (name, mode, self.dry_run)
Greg Ward013f0c82000-03-01 14:43:12 +0000944
Greg Warde1aaaa61999-08-14 23:50:50 +0000945
Greg Ward3f81cf71999-07-10 02:03:53 +0000946# class CCompiler
947
948
Marc-André Lemburg636b9062001-02-19 09:20:04 +0000949# Map a sys.platform/os.name ('posix', 'nt') to the default compiler
950# type for that platform. Keys are interpreted as re match
951# patterns. Order is important; platform mappings are preferred over
952# OS names.
953_default_compilers = (
954
955 # Platform string mappings
Andrew M. Kuchlinga34dbe02001-02-27 19:13:15 +0000956
957 # on a cygwin built python we can use gcc like an ordinary UNIXish
958 # compiler
959 ('cygwin.*', 'unix'),
Marc-André Lemburg2544f512002-01-31 18:56:00 +0000960 ('os2emx', 'emx'),
Fred Drakeb94b8492001-12-06 20:51:35 +0000961
Marc-André Lemburg636b9062001-02-19 09:20:04 +0000962 # OS name mappings
963 ('posix', 'unix'),
964 ('nt', 'msvc'),
965 ('mac', 'mwerks'),
Fred Drakeb94b8492001-12-06 20:51:35 +0000966
Marc-André Lemburg636b9062001-02-19 09:20:04 +0000967 )
968
969def get_default_compiler(osname=None, platform=None):
970
971 """ Determine the default compiler to use for the given platform.
972
973 osname should be one of the standard Python OS names (i.e. the
974 ones returned by os.name) and platform the common value
975 returned by sys.platform for the platform in question.
976
977 The default values are os.name and sys.platform in case the
978 parameters are not given.
979
980 """
981 if osname is None:
982 osname = os.name
983 if platform is None:
984 platform = sys.platform
985 for pattern, compiler in _default_compilers:
986 if re.match(pattern, platform) is not None or \
987 re.match(pattern, osname) is not None:
988 return compiler
989 # Default to Unix compiler
990 return 'unix'
Greg Ward802d6b71999-09-29 12:20:55 +0000991
992# Map compiler types to (module_name, class_name) pairs -- ie. where to
993# find the code that implements an interface to this compiler. (The module
994# is assumed to be in the 'distutils' package.)
Greg Ward2ff78872000-06-24 00:23:20 +0000995compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler',
996 "standard UNIX-style compiler"),
997 'msvc': ('msvccompiler', 'MSVCCompiler',
998 "Microsoft Visual C++"),
999 'cygwin': ('cygwinccompiler', 'CygwinCCompiler',
1000 "Cygwin port of GNU C Compiler for Win32"),
1001 'mingw32': ('cygwinccompiler', 'Mingw32CCompiler',
1002 "Mingw32 port of GNU C Compiler for Win32"),
Greg Wardbfc79d62000-06-28 01:29:09 +00001003 'bcpp': ('bcppcompiler', 'BCPPCompiler',
1004 "Borland C++ Compiler"),
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +00001005 'mwerks': ('mwerkscompiler', 'MWerksCompiler',
1006 "MetroWerks CodeWarrior"),
Marc-André Lemburg2544f512002-01-31 18:56:00 +00001007 'emx': ('emxccompiler', 'EMXCCompiler',
1008 "EMX port of GNU C Compiler for OS/2"),
Greg Ward802d6b71999-09-29 12:20:55 +00001009 }
1010
Greg Ward9d17a7a2000-06-07 03:00:06 +00001011def show_compilers():
Greg Ward2ff78872000-06-24 00:23:20 +00001012 """Print list of available compilers (used by the "--help-compiler"
1013 options to "build", "build_ext", "build_clib").
1014 """
1015 # XXX this "knows" that the compiler option it's describing is
1016 # "--compiler", which just happens to be the case for the three
1017 # commands that use it.
Fred Drakeb94b8492001-12-06 20:51:35 +00001018 from distutils.fancy_getopt import FancyGetopt
Greg Ward2ff78872000-06-24 00:23:20 +00001019 compilers = []
Greg Ward9d17a7a2000-06-07 03:00:06 +00001020 for compiler in compiler_class.keys():
Jeremy Hylton65d6edb2000-07-07 20:45:21 +00001021 compilers.append(("compiler="+compiler, None,
Greg Ward2ff78872000-06-24 00:23:20 +00001022 compiler_class[compiler][2]))
1023 compilers.sort()
1024 pretty_printer = FancyGetopt(compilers)
Greg Ward9d17a7a2000-06-07 03:00:06 +00001025 pretty_printer.print_help("List of available compilers:")
Fred Drakeb94b8492001-12-06 20:51:35 +00001026
Greg Ward802d6b71999-09-29 12:20:55 +00001027
Greg Warde1aaaa61999-08-14 23:50:50 +00001028def new_compiler (plat=None,
Greg Ward802d6b71999-09-29 12:20:55 +00001029 compiler=None,
Greg Warde1aaaa61999-08-14 23:50:50 +00001030 verbose=0,
Greg Ward3febd601999-10-03 20:41:02 +00001031 dry_run=0,
1032 force=0):
Greg Ward802d6b71999-09-29 12:20:55 +00001033 """Generate an instance of some CCompiler subclass for the supplied
Greg Wardc3a43b42000-06-24 18:10:48 +00001034 platform/compiler combination. 'plat' defaults to 'os.name'
1035 (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
1036 for that platform. Currently only 'posix' and 'nt' are supported, and
1037 the default compilers are "traditional Unix interface" (UnixCCompiler
1038 class) and Visual C++ (MSVCCompiler class). Note that it's perfectly
1039 possible to ask for a Unix compiler object under Windows, and a
1040 Microsoft compiler object under Unix -- if you supply a value for
1041 'compiler', 'plat' is ignored.
1042 """
Greg Ward802d6b71999-09-29 12:20:55 +00001043 if plat is None:
1044 plat = os.name
1045
1046 try:
1047 if compiler is None:
Marc-André Lemburg636b9062001-02-19 09:20:04 +00001048 compiler = get_default_compiler(plat)
Fred Drakeb94b8492001-12-06 20:51:35 +00001049
Greg Ward2ff78872000-06-24 00:23:20 +00001050 (module_name, class_name, long_description) = compiler_class[compiler]
Greg Ward802d6b71999-09-29 12:20:55 +00001051 except KeyError:
1052 msg = "don't know how to compile C/C++ code on platform '%s'" % plat
1053 if compiler is not None:
1054 msg = msg + " with '%s' compiler" % compiler
1055 raise DistutilsPlatformError, msg
Fred Drakeb94b8492001-12-06 20:51:35 +00001056
Greg Ward802d6b71999-09-29 12:20:55 +00001057 try:
1058 module_name = "distutils." + module_name
1059 __import__ (module_name)
1060 module = sys.modules[module_name]
1061 klass = vars(module)[class_name]
1062 except ImportError:
1063 raise DistutilsModuleError, \
1064 "can't compile C/C++ code: unable to load module '%s'" % \
1065 module_name
1066 except KeyError:
1067 raise DistutilsModuleError, \
1068 ("can't compile C/C++ code: unable to find class '%s' " +
1069 "in module '%s'") % (class_name, module_name)
1070
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +00001071 # XXX The None is necessary to preserve backwards compatibility
1072 # with classes that expect verbose to be the first positional
1073 # argument.
1074 return klass (None, dry_run, force)
Greg Wardf7a39ec1999-09-08 02:29:08 +00001075
1076
Greg Ward0bdd90a1999-12-12 17:19:58 +00001077def gen_preprocess_options (macros, include_dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +00001078 """Generate C pre-processor options (-D, -U, -I) as used by at least
1079 two types of compilers: the typical Unix compiler and Visual C++.
1080 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
1081 means undefine (-U) macro 'name', and (name,value) means define (-D)
1082 macro 'name' to 'value'. 'include_dirs' is just a list of directory
1083 names to be added to the header file search path (-I). Returns a list
1084 of command-line options suitable for either Unix compilers or Visual
1085 C++.
1086 """
Greg Wardf7a39ec1999-09-08 02:29:08 +00001087 # XXX it would be nice (mainly aesthetic, and so we don't generate
1088 # stupid-looking command lines) to go over 'macros' and eliminate
1089 # redundant definitions/undefinitions (ie. ensure that only the
1090 # latest mention of a particular macro winds up on the command
1091 # line). I don't think it's essential, though, since most (all?)
1092 # Unix C compilers only pay attention to the latest -D or -U
1093 # mention of a macro on their command line. Similar situation for
Greg Ward0bdd90a1999-12-12 17:19:58 +00001094 # 'include_dirs'. I'm punting on both for now. Anyways, weeding out
Greg Wardf7a39ec1999-09-08 02:29:08 +00001095 # redundancies like this should probably be the province of
1096 # CCompiler, since the data structures used are inherited from it
1097 # and therefore common to all CCompiler classes.
1098
1099 pp_opts = []
1100 for macro in macros:
Greg Wardfbf8aff1999-09-21 18:35:09 +00001101
1102 if not (type (macro) is TupleType and
1103 1 <= len (macro) <= 2):
1104 raise TypeError, \
1105 ("bad macro definition '%s': " +
1106 "each element of 'macros' list must be a 1- or 2-tuple") % \
1107 macro
1108
Greg Wardf7a39ec1999-09-08 02:29:08 +00001109 if len (macro) == 1: # undefine this macro
1110 pp_opts.append ("-U%s" % macro[0])
1111 elif len (macro) == 2:
1112 if macro[1] is None: # define with no explicit value
1113 pp_opts.append ("-D%s" % macro[0])
1114 else:
1115 # XXX *don't* need to be clever about quoting the
1116 # macro value here, because we're going to avoid the
1117 # shell at all costs when we spawn the command!
1118 pp_opts.append ("-D%s=%s" % macro)
1119
Greg Ward0bdd90a1999-12-12 17:19:58 +00001120 for dir in include_dirs:
Greg Wardf7a39ec1999-09-08 02:29:08 +00001121 pp_opts.append ("-I%s" % dir)
1122
1123 return pp_opts
1124
1125# gen_preprocess_options ()
1126
1127
Greg Wardd03f88a2000-03-18 15:19:51 +00001128def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
Greg Wardf7a39ec1999-09-08 02:29:08 +00001129 """Generate linker options for searching library directories and
Greg Wardc3a43b42000-06-24 18:10:48 +00001130 linking with specific libraries. 'libraries' and 'library_dirs' are,
1131 respectively, lists of library names (not filenames!) and search
1132 directories. Returns a list of command-line options suitable for use
1133 with some compiler (depending on the two format strings passed in).
1134 """
Greg Wardf7a39ec1999-09-08 02:29:08 +00001135 lib_opts = []
1136
1137 for dir in library_dirs:
Greg Ward3febd601999-10-03 20:41:02 +00001138 lib_opts.append (compiler.library_dir_option (dir))
Greg Wardf7a39ec1999-09-08 02:29:08 +00001139
Greg Wardd03f88a2000-03-18 15:19:51 +00001140 for dir in runtime_library_dirs:
1141 lib_opts.append (compiler.runtime_library_dir_option (dir))
1142
Greg Wardf7a39ec1999-09-08 02:29:08 +00001143 # XXX it's important that we *not* remove redundant library mentions!
1144 # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
1145 # resolve all symbols. I just hope we never have to say "-lfoo obj.o
1146 # -lbar" to get things to work -- that's certainly a possibility, but a
1147 # pretty nasty way to arrange your C code.
1148
1149 for lib in libraries:
Greg Ward3febd601999-10-03 20:41:02 +00001150 (lib_dir, lib_name) = os.path.split (lib)
1151 if lib_dir:
1152 lib_file = compiler.find_library_file ([lib_dir], lib_name)
1153 if lib_file:
1154 lib_opts.append (lib_file)
1155 else:
1156 compiler.warn ("no library file corresponding to "
1157 "'%s' found (skipping)" % lib)
1158 else:
1159 lib_opts.append (compiler.library_option (lib))
Greg Wardf7a39ec1999-09-08 02:29:08 +00001160
1161 return lib_opts
1162
Greg Ward32c4a8a2000-03-06 03:40:29 +00001163# gen_lib_options ()