blob: 4c8b881c3a4beea7cb7aa052b08503d0c792cc73 [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
163
Greg Ward3f81cf71999-07-10 02:03:53 +0000164 def _find_macro (self, name):
165 i = 0
166 for defn in self.macros:
167 if defn[0] == name:
168 return i
169 i = i + 1
170
171 return None
172
173
174 def _check_macro_definitions (self, definitions):
175 """Ensures that every element of 'definitions' is a valid macro
Greg Wardc3a43b42000-06-24 18:10:48 +0000176 definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do
177 nothing if all definitions are OK, raise TypeError otherwise.
178 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000179 for defn in definitions:
180 if not (type (defn) is TupleType and
181 (len (defn) == 1 or
182 (len (defn) == 2 and
183 (type (defn[1]) is StringType or defn[1] is None))) and
184 type (defn[0]) is StringType):
185 raise TypeError, \
186 ("invalid macro definition '%s': " % defn) + \
187 "must be tuple (string,), (string, string), or " + \
188 "(string, None)"
189
190
191 # -- Bookkeeping methods -------------------------------------------
192
193 def define_macro (self, name, value=None):
Greg Wardc3a43b42000-06-24 18:10:48 +0000194 """Define a preprocessor macro for all compilations driven by this
195 compiler object. The optional parameter 'value' should be a
196 string; if it is not supplied, then the macro will be defined
197 without an explicit value and the exact outcome depends on the
198 compiler used (XXX true? does ANSI say anything about this?)
199 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000200 # Delete from the list of macro definitions/undefinitions if
201 # already there (so that this one will take precedence).
202 i = self._find_macro (name)
203 if i is not None:
204 del self.macros[i]
205
206 defn = (name, value)
207 self.macros.append (defn)
208
209
210 def undefine_macro (self, name):
211 """Undefine a preprocessor macro for all compilations driven by
Greg Wardc3a43b42000-06-24 18:10:48 +0000212 this compiler object. If the same macro is defined by
213 'define_macro()' and undefined by 'undefine_macro()' the last call
214 takes precedence (including multiple redefinitions or
215 undefinitions). If the macro is redefined/undefined on a
216 per-compilation basis (ie. in the call to 'compile()'), then that
217 takes precedence.
218 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000219 # Delete from the list of macro definitions/undefinitions if
220 # already there (so that this one will take precedence).
221 i = self._find_macro (name)
222 if i is not None:
223 del self.macros[i]
224
225 undefn = (name,)
226 self.macros.append (undefn)
227
228
229 def add_include_dir (self, dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000230 """Add 'dir' to the list of directories that will be searched for
231 header files. The compiler is instructed to search directories in
232 the order in which they are supplied by successive calls to
233 'add_include_dir()'.
234 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000235 self.include_dirs.append (dir)
236
237 def set_include_dirs (self, dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000238 """Set the list of directories that will be searched to 'dirs' (a
239 list of strings). Overrides any preceding calls to
240 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
241 to the list passed to 'set_include_dirs()'. This does not affect
242 any list of standard include directories that the compiler may
243 search by default.
244 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000245 self.include_dirs = copy (dirs)
246
247
248 def add_library (self, libname):
Greg Wardc3a43b42000-06-24 18:10:48 +0000249 """Add 'libname' to the list of libraries that will be included in
250 all links driven by this compiler object. Note that 'libname'
251 should *not* be the name of a file containing a library, but the
252 name of the library itself: the actual filename will be inferred by
253 the linker, the compiler, or the compiler class (depending on the
254 platform).
Greg Ward3f81cf71999-07-10 02:03:53 +0000255
Greg Wardc3a43b42000-06-24 18:10:48 +0000256 The linker will be instructed to link against libraries in the
257 order they were supplied to 'add_library()' and/or
258 'set_libraries()'. It is perfectly valid to duplicate library
259 names; the linker will be instructed to link against libraries as
260 many times as they are mentioned.
261 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000262 self.libraries.append (libname)
263
264 def set_libraries (self, libnames):
Greg Wardc3a43b42000-06-24 18:10:48 +0000265 """Set the list of libraries to be included in all links driven by
266 this compiler object to 'libnames' (a list of strings). This does
267 not affect any standard system libraries that the linker may
268 include by default.
269 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000270 self.libraries = copy (libnames)
271
272
273 def add_library_dir (self, dir):
274 """Add 'dir' to the list of directories that will be searched for
Greg Wardc3a43b42000-06-24 18:10:48 +0000275 libraries specified to 'add_library()' and 'set_libraries()'. The
276 linker will be instructed to search for libraries in the order they
277 are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
278 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000279 self.library_dirs.append (dir)
280
281 def set_library_dirs (self, dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000282 """Set the list of library search directories to 'dirs' (a list of
283 strings). This does not affect any standard library search path
284 that the linker may search by default.
285 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000286 self.library_dirs = copy (dirs)
287
288
Greg Warde1aaaa61999-08-14 23:50:50 +0000289 def add_runtime_library_dir (self, dir):
290 """Add 'dir' to the list of directories that will be searched for
Greg Wardc3a43b42000-06-24 18:10:48 +0000291 shared libraries at runtime.
292 """
Greg Warde1aaaa61999-08-14 23:50:50 +0000293 self.runtime_library_dirs.append (dir)
294
295 def set_runtime_library_dirs (self, dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000296 """Set the list of directories to search for shared libraries at
297 runtime to 'dirs' (a list of strings). This does not affect any
298 standard search path that the runtime linker may search by
299 default.
300 """
Greg Warde1aaaa61999-08-14 23:50:50 +0000301 self.runtime_library_dirs = copy (dirs)
302
303
Greg Ward3f81cf71999-07-10 02:03:53 +0000304 def add_link_object (self, object):
Greg Wardc3a43b42000-06-24 18:10:48 +0000305 """Add 'object' to the list of object files (or analogues, such as
Greg Ward612eb9f2000-07-27 02:13:20 +0000306 explicitly named library files or the output of "resource
Greg Wardc3a43b42000-06-24 18:10:48 +0000307 compilers") to be included in every link driven by this compiler
308 object.
309 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000310 self.objects.append (object)
311
312 def set_link_objects (self, objects):
Greg Wardc3a43b42000-06-24 18:10:48 +0000313 """Set the list of object files (or analogues) to be included in
314 every link to 'objects'. This does not affect any standard object
315 files that the linker may include by default (such as system
316 libraries).
317 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000318 self.objects = copy (objects)
319
320
Thomas Hellere6500802002-04-25 17:03:30 +0000321 # -- Private utility methods --------------------------------------
Greg Ward32c4a8a2000-03-06 03:40:29 +0000322 # (here for the convenience of subclasses)
323
324 def _fix_compile_args (self, output_dir, macros, include_dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000325 """Typecheck and fix-up some of the arguments to the 'compile()'
326 method, and return fixed-up values. Specifically: if 'output_dir'
327 is None, replaces it with 'self.output_dir'; ensures that 'macros'
328 is a list, and augments it with 'self.macros'; ensures that
329 'include_dirs' is a list, and augments it with 'self.include_dirs'.
330 Guarantees that the returned values are of the correct type,
331 i.e. for 'output_dir' either string or None, and for 'macros' and
332 'include_dirs' either list or None.
333 """
Greg Ward32c4a8a2000-03-06 03:40:29 +0000334 if output_dir is None:
335 output_dir = self.output_dir
336 elif type (output_dir) is not StringType:
337 raise TypeError, "'output_dir' must be a string or None"
338
339 if macros is None:
340 macros = self.macros
341 elif type (macros) is ListType:
342 macros = macros + (self.macros or [])
343 else:
344 raise TypeError, \
345 "'macros' (if supplied) must be a list of tuples"
346
347 if include_dirs is None:
348 include_dirs = self.include_dirs
349 elif type (include_dirs) in (ListType, TupleType):
350 include_dirs = list (include_dirs) + (self.include_dirs or [])
351 else:
352 raise TypeError, \
353 "'include_dirs' (if supplied) must be a list of strings"
Fred Drakeb94b8492001-12-06 20:51:35 +0000354
Greg Ward32c4a8a2000-03-06 03:40:29 +0000355 return (output_dir, macros, include_dirs)
356
357 # _fix_compile_args ()
358
359
360 def _prep_compile (self, sources, output_dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000361 """Determine the list of object files corresponding to 'sources',
362 and figure out which ones really need to be recompiled. Return a
363 list of all object files and a dictionary telling which source
364 files can be skipped.
365 """
Fred Drakeb94b8492001-12-06 20:51:35 +0000366 # Get the list of expected output (object) files
Greg Ward32c4a8a2000-03-06 03:40:29 +0000367 objects = self.object_filenames (sources,
Andrew M. Kuchlingbd2983c2001-01-16 03:10:43 +0000368 strip_dir=1,
Greg Ward32c4a8a2000-03-06 03:40:29 +0000369 output_dir=output_dir)
370
371 if self.force:
372 skip_source = {} # rebuild everything
373 for source in sources:
374 skip_source[source] = 0
375 else:
376 # Figure out which source files we have to recompile according
377 # to a simplistic check -- we just compare the source and
378 # object file, no deep dependency checking involving header
379 # files.
380 skip_source = {} # rebuild everything
381 for source in sources: # no wait, rebuild nothing
382 skip_source[source] = 1
383
384 (n_sources, n_objects) = newer_pairwise (sources, objects)
Greg Wardc3a43b42000-06-24 18:10:48 +0000385 for source in n_sources: # no really, only rebuild what's
386 skip_source[source] = 0 # out-of-date
Greg Ward32c4a8a2000-03-06 03:40:29 +0000387
388 return (objects, skip_source)
389
390 # _prep_compile ()
391
392
Greg Wardf10f95d2000-03-26 21:37:09 +0000393 def _fix_object_args (self, objects, output_dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000394 """Typecheck and fix up some arguments supplied to various methods.
395 Specifically: ensure that 'objects' is a list; if output_dir is
396 None, replace with self.output_dir. Return fixed versions of
397 'objects' and 'output_dir'.
398 """
Greg Ward32c4a8a2000-03-06 03:40:29 +0000399 if type (objects) not in (ListType, TupleType):
400 raise TypeError, \
401 "'objects' must be a list or tuple of strings"
402 objects = list (objects)
Fred Drakeb94b8492001-12-06 20:51:35 +0000403
Greg Ward32c4a8a2000-03-06 03:40:29 +0000404 if output_dir is None:
405 output_dir = self.output_dir
406 elif type (output_dir) is not StringType:
407 raise TypeError, "'output_dir' must be a string or None"
408
Greg Wardf10f95d2000-03-26 21:37:09 +0000409 return (objects, output_dir)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000410
Greg Ward32c4a8a2000-03-06 03:40:29 +0000411
Greg Wardf10f95d2000-03-26 21:37:09 +0000412 def _fix_lib_args (self, libraries, library_dirs, runtime_library_dirs):
413 """Typecheck and fix up some of the arguments supplied to the
Greg Wardc3a43b42000-06-24 18:10:48 +0000414 'link_*' methods. Specifically: ensure that all arguments are
415 lists, and augment them with their permanent versions
416 (eg. 'self.libraries' augments 'libraries'). Return a tuple with
417 fixed versions of all arguments.
418 """
Greg Wardf10f95d2000-03-26 21:37:09 +0000419 if libraries is None:
420 libraries = self.libraries
421 elif type (libraries) in (ListType, TupleType):
422 libraries = list (libraries) + (self.libraries or [])
Greg Ward32c4a8a2000-03-06 03:40:29 +0000423 else:
Greg Wardf10f95d2000-03-26 21:37:09 +0000424 raise TypeError, \
425 "'libraries' (if supplied) must be a list of strings"
Greg Ward32c4a8a2000-03-06 03:40:29 +0000426
Greg Wardf10f95d2000-03-26 21:37:09 +0000427 if library_dirs is None:
428 library_dirs = self.library_dirs
429 elif type (library_dirs) in (ListType, TupleType):
430 library_dirs = list (library_dirs) + (self.library_dirs or [])
431 else:
432 raise TypeError, \
433 "'library_dirs' (if supplied) must be a list of strings"
434
435 if runtime_library_dirs is None:
436 runtime_library_dirs = self.runtime_library_dirs
437 elif type (runtime_library_dirs) in (ListType, TupleType):
438 runtime_library_dirs = (list (runtime_library_dirs) +
439 (self.runtime_library_dirs or []))
440 else:
441 raise TypeError, \
442 "'runtime_library_dirs' (if supplied) " + \
443 "must be a list of strings"
444
445 return (libraries, library_dirs, runtime_library_dirs)
446
447 # _fix_lib_args ()
Greg Ward32c4a8a2000-03-06 03:40:29 +0000448
449
450 def _need_link (self, objects, output_file):
Greg Wardc3a43b42000-06-24 18:10:48 +0000451 """Return true if we need to relink the files listed in 'objects'
452 to recreate 'output_file'.
453 """
Greg Ward32c4a8a2000-03-06 03:40:29 +0000454 if self.force:
455 return 1
456 else:
457 if self.dry_run:
458 newer = newer_group (objects, output_file, missing='newer')
459 else:
460 newer = newer_group (objects, output_file)
461 return newer
462
463 # _need_link ()
464
465
Greg Ward3f81cf71999-07-10 02:03:53 +0000466 # -- Worker methods ------------------------------------------------
467 # (must be implemented by subclasses)
468
Greg Ward3ff3b032000-06-21 02:58:46 +0000469 def preprocess (self,
470 source,
471 output_file=None,
472 macros=None,
473 include_dirs=None,
474 extra_preargs=None,
475 extra_postargs=None):
476 """Preprocess a single C/C++ source file, named in 'source'.
477 Output will be written to file named 'output_file', or stdout if
478 'output_file' not supplied. 'macros' is a list of macro
479 definitions as for 'compile()', which will augment the macros set
480 with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a
481 list of directory names that will be added to the default list.
Greg Warde5c62bf2000-06-25 02:08:18 +0000482
483 Raises PreprocessError on failure.
Greg Ward3ff3b032000-06-21 02:58:46 +0000484 """
485 pass
486
Greg Ward3f81cf71999-07-10 02:03:53 +0000487 def compile (self,
488 sources,
Greg Ward9b17cb51999-09-13 03:07:24 +0000489 output_dir=None,
Greg Ward3f81cf71999-07-10 02:03:53 +0000490 macros=None,
Greg Ward0bdd90a1999-12-12 17:19:58 +0000491 include_dirs=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000492 debug=0,
Greg Ward802d6b71999-09-29 12:20:55 +0000493 extra_preargs=None,
494 extra_postargs=None):
Greg Warde5c62bf2000-06-25 02:08:18 +0000495 """Compile one or more source files. 'sources' must be a list of
496 filenames, most likely C/C++ files, but in reality anything that
497 can be handled by a particular compiler and compiler class
498 (eg. MSVCCompiler can handle resource files in 'sources'). Return
Greg Wardc3a43b42000-06-24 18:10:48 +0000499 a list of object filenames, one per source filename in 'sources'.
500 Depending on the implementation, not all source files will
501 necessarily be compiled, but all corresponding object filenames
502 will be returned.
Greg Ward32c4a8a2000-03-06 03:40:29 +0000503
Greg Wardc3a43b42000-06-24 18:10:48 +0000504 If 'output_dir' is given, object files will be put under it, while
505 retaining their original path component. That is, "foo/bar.c"
506 normally compiles to "foo/bar.o" (for a Unix implementation); if
507 'output_dir' is "build", then it would compile to
508 "build/foo/bar.o".
Greg Ward3f81cf71999-07-10 02:03:53 +0000509
Greg Wardc3a43b42000-06-24 18:10:48 +0000510 'macros', if given, must be a list of macro definitions. A macro
511 definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
512 The former defines a macro; if the value is None, the macro is
513 defined without an explicit value. The 1-tuple case undefines a
514 macro. Later definitions/redefinitions/ undefinitions take
515 precedence.
Greg Ward3f81cf71999-07-10 02:03:53 +0000516
Greg Wardc3a43b42000-06-24 18:10:48 +0000517 'include_dirs', if given, must be a list of strings, the
518 directories to add to the default include file search path for this
519 compilation only.
Greg Ward3c045a52000-02-09 02:16:14 +0000520
Greg Wardc3a43b42000-06-24 18:10:48 +0000521 'debug' is a boolean; if true, the compiler will be instructed to
522 output debug symbols in (or alongside) the object file(s).
Greg Ward802d6b71999-09-29 12:20:55 +0000523
Greg Wardc3a43b42000-06-24 18:10:48 +0000524 'extra_preargs' and 'extra_postargs' are implementation- dependent.
525 On platforms that have the notion of a command-line (e.g. Unix,
526 DOS/Windows), they are most likely lists of strings: extra
527 command-line arguments to prepand/append to the compiler command
528 line. On other platforms, consult the implementation class
529 documentation. In any event, they are intended as an escape hatch
530 for those occasions when the abstract compiler framework doesn't
531 cut the mustard.
Greg Wardd1517112000-05-30 01:56:44 +0000532
Greg Wardc3a43b42000-06-24 18:10:48 +0000533 Raises CompileError on failure.
534 """
Greg Ward3f81cf71999-07-10 02:03:53 +0000535 pass
536
537
Greg Ward036c8052000-03-10 01:48:32 +0000538 def create_static_lib (self,
539 objects,
540 output_libname,
541 output_dir=None,
542 debug=0):
Greg Wardc3a43b42000-06-24 18:10:48 +0000543 """Link a bunch of stuff together to create a static library file.
544 The "bunch of stuff" consists of the list of object files supplied
545 as 'objects', the extra object files supplied to
546 'add_link_object()' and/or 'set_link_objects()', the libraries
547 supplied to 'add_library()' and/or 'set_libraries()', and the
548 libraries supplied as 'libraries' (if any).
Greg Ward3f81cf71999-07-10 02:03:53 +0000549
Greg Wardc3a43b42000-06-24 18:10:48 +0000550 'output_libname' should be a library name, not a filename; the
551 filename will be inferred from the library name. 'output_dir' is
552 the directory where the library file will be put.
Greg Ward3c045a52000-02-09 02:16:14 +0000553
Greg Wardc3a43b42000-06-24 18:10:48 +0000554 'debug' is a boolean; if true, debugging information will be
555 included in the library (note that on most platforms, it is the
556 compile step where this matters: the 'debug' flag is included here
557 just for consistency).
Greg Wardd1517112000-05-30 01:56:44 +0000558
Greg Wardc3a43b42000-06-24 18:10:48 +0000559 Raises LibError on failure.
560 """
Greg Ward3c045a52000-02-09 02:16:14 +0000561 pass
Fred Drakeb94b8492001-12-06 20:51:35 +0000562
Greg Ward3c045a52000-02-09 02:16:14 +0000563
Greg Ward42406482000-09-27 02:08:14 +0000564 # values for target_desc parameter in link()
565 SHARED_OBJECT = "shared_object"
566 SHARED_LIBRARY = "shared_library"
567 EXECUTABLE = "executable"
568
569 def link (self,
570 target_desc,
571 objects,
572 output_filename,
573 output_dir=None,
574 libraries=None,
575 library_dirs=None,
576 runtime_library_dirs=None,
577 export_symbols=None,
578 debug=0,
579 extra_preargs=None,
580 extra_postargs=None,
581 build_temp=None):
582 """Link a bunch of stuff together to create an executable or
583 shared library file.
584
585 The "bunch of stuff" consists of the list of object files supplied
586 as 'objects'. 'output_filename' should be a filename. If
587 'output_dir' is supplied, 'output_filename' is relative to it
588 (i.e. 'output_filename' can provide directory components if
589 needed).
Greg Ward3febd601999-10-03 20:41:02 +0000590
Greg Wardc3a43b42000-06-24 18:10:48 +0000591 'libraries' is a list of libraries to link against. These are
592 library names, not filenames, since they're translated into
593 filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
594 on Unix and "foo.lib" on DOS/Windows). However, they can include a
595 directory component, which means the linker will look in that
596 specific directory rather than searching all the normal locations.
Greg Ward5299b6a2000-05-20 13:23:21 +0000597
Greg Wardc3a43b42000-06-24 18:10:48 +0000598 'library_dirs', if supplied, should be a list of directories to
599 search for libraries that were specified as bare library names
600 (ie. no directory component). These are on top of the system
601 default and those supplied to 'add_library_dir()' and/or
602 'set_library_dirs()'. 'runtime_library_dirs' is a list of
603 directories that will be embedded into the shared library and used
604 to search for other shared libraries that *it* depends on at
605 run-time. (This may only be relevant on Unix.)
Greg Ward802d6b71999-09-29 12:20:55 +0000606
Greg Wardc3a43b42000-06-24 18:10:48 +0000607 'export_symbols' is a list of symbols that the shared library will
608 export. (This appears to be relevant only on Windows.)
Greg Ward3c045a52000-02-09 02:16:14 +0000609
Greg Wardc3a43b42000-06-24 18:10:48 +0000610 'debug' is as for 'compile()' and 'create_static_lib()', with the
611 slight distinction that it actually matters on most platforms (as
612 opposed to 'create_static_lib()', which includes a 'debug' flag
613 mostly for form's sake).
Greg Wardd1517112000-05-30 01:56:44 +0000614
Greg Wardc3a43b42000-06-24 18:10:48 +0000615 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
616 of course that they supply command-line arguments for the
617 particular linker being used).
Greg Ward3f81cf71999-07-10 02:03:53 +0000618
Greg Wardc3a43b42000-06-24 18:10:48 +0000619 Raises LinkError on failure.
620 """
Greg Ward42406482000-09-27 02:08:14 +0000621 raise NotImplementedError
622
Fred Drakeb94b8492001-12-06 20:51:35 +0000623
Greg Ward264cf742000-09-27 02:24:21 +0000624 # Old 'link_*()' methods, rewritten to use the new 'link()' method.
Greg Ward42406482000-09-27 02:08:14 +0000625
626 def link_shared_lib (self,
627 objects,
628 output_libname,
629 output_dir=None,
630 libraries=None,
631 library_dirs=None,
632 runtime_library_dirs=None,
633 export_symbols=None,
634 debug=0,
635 extra_preargs=None,
636 extra_postargs=None,
637 build_temp=None):
Fred Drakeb94b8492001-12-06 20:51:35 +0000638 self.link(CCompiler.SHARED_LIBRARY, objects,
Greg Ward42406482000-09-27 02:08:14 +0000639 self.library_filename(output_libname, lib_type='shared'),
640 output_dir,
641 libraries, library_dirs, runtime_library_dirs,
642 export_symbols, debug,
643 extra_preargs, extra_postargs, build_temp)
Fred Drakeb94b8492001-12-06 20:51:35 +0000644
Greg Ward3f81cf71999-07-10 02:03:53 +0000645
Greg Ward3f81cf71999-07-10 02:03:53 +0000646 def link_shared_object (self,
647 objects,
648 output_filename,
Greg Ward9b17cb51999-09-13 03:07:24 +0000649 output_dir=None,
Greg Ward3f81cf71999-07-10 02:03:53 +0000650 libraries=None,
Greg Ward26e48ea1999-08-29 18:17:36 +0000651 library_dirs=None,
Greg Wardf10f95d2000-03-26 21:37:09 +0000652 runtime_library_dirs=None,
Greg Ward5299b6a2000-05-20 13:23:21 +0000653 export_symbols=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000654 debug=0,
Greg Ward802d6b71999-09-29 12:20:55 +0000655 extra_preargs=None,
Greg Wardbfc79d62000-06-28 01:29:09 +0000656 extra_postargs=None,
657 build_temp=None):
Greg Ward42406482000-09-27 02:08:14 +0000658 self.link(CCompiler.SHARED_OBJECT, objects,
659 output_filename, output_dir,
660 libraries, library_dirs, runtime_library_dirs,
661 export_symbols, debug,
662 extra_preargs, extra_postargs, build_temp)
Greg Ward3f81cf71999-07-10 02:03:53 +0000663
Greg Warde1aaaa61999-08-14 23:50:50 +0000664
Greg Ward5baf1c22000-01-09 22:41:02 +0000665 def link_executable (self,
666 objects,
667 output_progname,
668 output_dir=None,
669 libraries=None,
670 library_dirs=None,
Greg Wardf10f95d2000-03-26 21:37:09 +0000671 runtime_library_dirs=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000672 debug=0,
Greg Ward5baf1c22000-01-09 22:41:02 +0000673 extra_preargs=None,
674 extra_postargs=None):
Fred Drakeb94b8492001-12-06 20:51:35 +0000675 self.link(CCompiler.EXECUTABLE, objects,
Greg Ward264cf742000-09-27 02:24:21 +0000676 self.executable_filename(output_progname), output_dir,
Fred Drakeb94b8492001-12-06 20:51:35 +0000677 libraries, library_dirs, runtime_library_dirs, None,
Greg Ward264cf742000-09-27 02:24:21 +0000678 debug, extra_preargs, extra_postargs, None)
Greg Ward5baf1c22000-01-09 22:41:02 +0000679
680
Greg Wardf7edea72000-05-20 13:31:32 +0000681 # -- Miscellaneous methods -----------------------------------------
682 # These are all used by the 'gen_lib_options() function; there is
683 # no appropriate default implementation so subclasses should
684 # implement all of these.
685
686 def library_dir_option (self, dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000687 """Return the compiler option to add 'dir' to the list of
688 directories searched for libraries.
689 """
Greg Wardf7edea72000-05-20 13:31:32 +0000690 raise NotImplementedError
691
692 def runtime_library_dir_option (self, dir):
Greg Wardc3a43b42000-06-24 18:10:48 +0000693 """Return the compiler option to add 'dir' to the list of
694 directories searched for runtime libraries.
695 """
Greg Wardf7edea72000-05-20 13:31:32 +0000696 raise NotImplementedError
697
698 def library_option (self, lib):
699 """Return the compiler option to add 'dir' to the list of libraries
Greg Wardc3a43b42000-06-24 18:10:48 +0000700 linked into the shared library or executable.
701 """
Greg Wardf7edea72000-05-20 13:31:32 +0000702 raise NotImplementedError
703
Greg Warde5e60152000-08-04 01:28:39 +0000704 def find_library_file (self, dirs, lib, debug=0):
Greg Wardf7edea72000-05-20 13:31:32 +0000705 """Search the specified list of directories for a static or shared
Greg Warde5e60152000-08-04 01:28:39 +0000706 library file 'lib' and return the full path to that file. If
707 'debug' true, look for a debugging version (if that makes sense on
708 the current platform). Return None if 'lib' wasn't found in any of
709 the specified directories.
Greg Wardc3a43b42000-06-24 18:10:48 +0000710 """
Greg Wardf7edea72000-05-20 13:31:32 +0000711 raise NotImplementedError
712
713
Greg Ward32c4a8a2000-03-06 03:40:29 +0000714 # -- Filename generation methods -----------------------------------
Greg Warde1aaaa61999-08-14 23:50:50 +0000715
Greg Ward32c4a8a2000-03-06 03:40:29 +0000716 # The default implementation of the filename generating methods are
717 # prejudiced towards the Unix/DOS/Windows view of the world:
718 # * object files are named by replacing the source file extension
719 # (eg. .c/.cpp -> .o/.obj)
720 # * library files (shared or static) are named by plugging the
721 # library name and extension into a format string, eg.
722 # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
723 # * executables are named by appending an extension (possibly
724 # empty) to the program name: eg. progname + ".exe" for
725 # Windows
726 #
727 # To reduce redundant code, these methods expect to find
728 # several attributes in the current object (presumably defined
729 # as class attributes):
730 # * src_extensions -
731 # list of C/C++ source file extensions, eg. ['.c', '.cpp']
732 # * obj_extension -
733 # object file extension, eg. '.o' or '.obj'
734 # * static_lib_extension -
735 # extension for static library files, eg. '.a' or '.lib'
736 # * shared_lib_extension -
737 # extension for shared library/object files, eg. '.so', '.dll'
738 # * static_lib_format -
739 # format string for generating static library filenames,
740 # eg. 'lib%s.%s' or '%s.%s'
741 # * shared_lib_format
742 # format string for generating shared library filenames
743 # (probably same as static_lib_format, since the extension
744 # is one of the intended parameters to the format string)
745 # * exe_extension -
746 # extension for executable files, eg. '' or '.exe'
Greg Ward9b17cb51999-09-13 03:07:24 +0000747
Greg Ward32c4a8a2000-03-06 03:40:29 +0000748 def object_filenames (self,
749 source_filenames,
750 strip_dir=0,
751 output_dir=''):
752 if output_dir is None: output_dir = ''
753 obj_names = []
754 for src_name in source_filenames:
755 (base, ext) = os.path.splitext (src_name)
756 if ext not in self.src_extensions:
Greg Ward9aa668b2000-06-24 02:22:49 +0000757 raise UnknownFileError, \
758 "unknown file type '%s' (from '%s')" % \
759 (ext, src_name)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000760 if strip_dir:
761 base = os.path.basename (base)
762 obj_names.append (os.path.join (output_dir,
763 base + self.obj_extension))
764 return obj_names
Greg Warde1aaaa61999-08-14 23:50:50 +0000765
Greg Ward32c4a8a2000-03-06 03:40:29 +0000766 # object_filenames ()
Greg Warde1aaaa61999-08-14 23:50:50 +0000767
Greg Warde1aaaa61999-08-14 23:50:50 +0000768
Greg Ward32c4a8a2000-03-06 03:40:29 +0000769 def shared_object_filename (self,
770 basename,
771 strip_dir=0,
772 output_dir=''):
773 if output_dir is None: output_dir = ''
774 if strip_dir:
775 basename = os.path.basename (basename)
776 return os.path.join (output_dir, basename + self.shared_lib_extension)
Greg Warde1aaaa61999-08-14 23:50:50 +0000777
Greg Ward42406482000-09-27 02:08:14 +0000778 def executable_filename (self,
779 basename,
780 strip_dir=0,
781 output_dir=''):
782 if output_dir is None: output_dir = ''
783 if strip_dir:
784 basename = os.path.basename (basename)
785 return os.path.join(output_dir, basename + (self.exe_extension or ''))
Greg Ward26e48ea1999-08-29 18:17:36 +0000786
Greg Ward32c4a8a2000-03-06 03:40:29 +0000787 def library_filename (self,
788 libname,
789 lib_type='static', # or 'shared'
790 strip_dir=0,
791 output_dir=''):
792
793 if output_dir is None: output_dir = ''
Jack Jansene259e592001-08-27 15:08:16 +0000794 if lib_type not in ("static","shared","dylib"):
795 raise ValueError, "'lib_type' must be \"static\", \"shared\" or \"dylib\""
Greg Ward32c4a8a2000-03-06 03:40:29 +0000796 fmt = getattr (self, lib_type + "_lib_format")
797 ext = getattr (self, lib_type + "_lib_extension")
798
799 (dir, base) = os.path.split (libname)
800 filename = fmt % (base, ext)
801 if strip_dir:
802 dir = ''
803
804 return os.path.join (output_dir, dir, filename)
805
Greg Warde1aaaa61999-08-14 23:50:50 +0000806
807 # -- Utility methods -----------------------------------------------
808
Greg Ward9b17cb51999-09-13 03:07:24 +0000809 def announce (self, msg, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000810 log.debug(msg)
Greg Ward9b17cb51999-09-13 03:07:24 +0000811
Greg Wardf813e592000-08-04 01:31:13 +0000812 def debug_print (self, msg):
813 from distutils.core import DEBUG
814 if DEBUG:
815 print msg
816
Greg Ward3febd601999-10-03 20:41:02 +0000817 def warn (self, msg):
818 sys.stderr.write ("warning: %s\n" % msg)
819
Greg Ward9dddbb42000-08-02 01:38:20 +0000820 def execute (self, func, args, msg=None, level=1):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000821 execute(func, args, msg, self.dry_run)
Greg Ward9dddbb42000-08-02 01:38:20 +0000822
Greg Warde1aaaa61999-08-14 23:50:50 +0000823 def spawn (self, cmd):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000824 spawn (cmd, dry_run=self.dry_run)
Greg Warde1aaaa61999-08-14 23:50:50 +0000825
Greg Ward9b17cb51999-09-13 03:07:24 +0000826 def move_file (self, src, dst):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000827 return move_file (src, dst, dry_run=self.dry_run)
Greg Ward9b17cb51999-09-13 03:07:24 +0000828
Greg Ward013f0c82000-03-01 14:43:12 +0000829 def mkpath (self, name, mode=0777):
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000830 mkpath (name, mode, self.dry_run)
Greg Ward013f0c82000-03-01 14:43:12 +0000831
Greg Warde1aaaa61999-08-14 23:50:50 +0000832
Greg Ward3f81cf71999-07-10 02:03:53 +0000833# class CCompiler
834
835
Marc-André Lemburg636b9062001-02-19 09:20:04 +0000836# Map a sys.platform/os.name ('posix', 'nt') to the default compiler
837# type for that platform. Keys are interpreted as re match
838# patterns. Order is important; platform mappings are preferred over
839# OS names.
840_default_compilers = (
841
842 # Platform string mappings
Andrew M. Kuchlinga34dbe02001-02-27 19:13:15 +0000843
844 # on a cygwin built python we can use gcc like an ordinary UNIXish
845 # compiler
846 ('cygwin.*', 'unix'),
Marc-André Lemburg2544f512002-01-31 18:56:00 +0000847 ('os2emx', 'emx'),
Fred Drakeb94b8492001-12-06 20:51:35 +0000848
Marc-André Lemburg636b9062001-02-19 09:20:04 +0000849 # OS name mappings
850 ('posix', 'unix'),
851 ('nt', 'msvc'),
852 ('mac', 'mwerks'),
Fred Drakeb94b8492001-12-06 20:51:35 +0000853
Marc-André Lemburg636b9062001-02-19 09:20:04 +0000854 )
855
856def get_default_compiler(osname=None, platform=None):
857
858 """ Determine the default compiler to use for the given platform.
859
860 osname should be one of the standard Python OS names (i.e. the
861 ones returned by os.name) and platform the common value
862 returned by sys.platform for the platform in question.
863
864 The default values are os.name and sys.platform in case the
865 parameters are not given.
866
867 """
868 if osname is None:
869 osname = os.name
870 if platform is None:
871 platform = sys.platform
872 for pattern, compiler in _default_compilers:
873 if re.match(pattern, platform) is not None or \
874 re.match(pattern, osname) is not None:
875 return compiler
876 # Default to Unix compiler
877 return 'unix'
Greg Ward802d6b71999-09-29 12:20:55 +0000878
879# Map compiler types to (module_name, class_name) pairs -- ie. where to
880# find the code that implements an interface to this compiler. (The module
881# is assumed to be in the 'distutils' package.)
Greg Ward2ff78872000-06-24 00:23:20 +0000882compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler',
883 "standard UNIX-style compiler"),
884 'msvc': ('msvccompiler', 'MSVCCompiler',
885 "Microsoft Visual C++"),
886 'cygwin': ('cygwinccompiler', 'CygwinCCompiler',
887 "Cygwin port of GNU C Compiler for Win32"),
888 'mingw32': ('cygwinccompiler', 'Mingw32CCompiler',
889 "Mingw32 port of GNU C Compiler for Win32"),
Greg Wardbfc79d62000-06-28 01:29:09 +0000890 'bcpp': ('bcppcompiler', 'BCPPCompiler',
891 "Borland C++ Compiler"),
Andrew M. Kuchling3f819ec2001-01-15 16:09:35 +0000892 'mwerks': ('mwerkscompiler', 'MWerksCompiler',
893 "MetroWerks CodeWarrior"),
Marc-André Lemburg2544f512002-01-31 18:56:00 +0000894 'emx': ('emxccompiler', 'EMXCCompiler',
895 "EMX port of GNU C Compiler for OS/2"),
Greg Ward802d6b71999-09-29 12:20:55 +0000896 }
897
Greg Ward9d17a7a2000-06-07 03:00:06 +0000898def show_compilers():
Greg Ward2ff78872000-06-24 00:23:20 +0000899 """Print list of available compilers (used by the "--help-compiler"
900 options to "build", "build_ext", "build_clib").
901 """
902 # XXX this "knows" that the compiler option it's describing is
903 # "--compiler", which just happens to be the case for the three
904 # commands that use it.
Fred Drakeb94b8492001-12-06 20:51:35 +0000905 from distutils.fancy_getopt import FancyGetopt
Greg Ward2ff78872000-06-24 00:23:20 +0000906 compilers = []
Greg Ward9d17a7a2000-06-07 03:00:06 +0000907 for compiler in compiler_class.keys():
Jeremy Hylton65d6edb2000-07-07 20:45:21 +0000908 compilers.append(("compiler="+compiler, None,
Greg Ward2ff78872000-06-24 00:23:20 +0000909 compiler_class[compiler][2]))
910 compilers.sort()
911 pretty_printer = FancyGetopt(compilers)
Greg Ward9d17a7a2000-06-07 03:00:06 +0000912 pretty_printer.print_help("List of available compilers:")
Fred Drakeb94b8492001-12-06 20:51:35 +0000913
Greg Ward802d6b71999-09-29 12:20:55 +0000914
Greg Warde1aaaa61999-08-14 23:50:50 +0000915def new_compiler (plat=None,
Greg Ward802d6b71999-09-29 12:20:55 +0000916 compiler=None,
Greg Warde1aaaa61999-08-14 23:50:50 +0000917 verbose=0,
Greg Ward3febd601999-10-03 20:41:02 +0000918 dry_run=0,
919 force=0):
Greg Ward802d6b71999-09-29 12:20:55 +0000920 """Generate an instance of some CCompiler subclass for the supplied
Greg Wardc3a43b42000-06-24 18:10:48 +0000921 platform/compiler combination. 'plat' defaults to 'os.name'
922 (eg. 'posix', 'nt'), and 'compiler' defaults to the default compiler
923 for that platform. Currently only 'posix' and 'nt' are supported, and
924 the default compilers are "traditional Unix interface" (UnixCCompiler
925 class) and Visual C++ (MSVCCompiler class). Note that it's perfectly
926 possible to ask for a Unix compiler object under Windows, and a
927 Microsoft compiler object under Unix -- if you supply a value for
928 'compiler', 'plat' is ignored.
929 """
Greg Ward802d6b71999-09-29 12:20:55 +0000930 if plat is None:
931 plat = os.name
932
933 try:
934 if compiler is None:
Marc-André Lemburg636b9062001-02-19 09:20:04 +0000935 compiler = get_default_compiler(plat)
Fred Drakeb94b8492001-12-06 20:51:35 +0000936
Greg Ward2ff78872000-06-24 00:23:20 +0000937 (module_name, class_name, long_description) = compiler_class[compiler]
Greg Ward802d6b71999-09-29 12:20:55 +0000938 except KeyError:
939 msg = "don't know how to compile C/C++ code on platform '%s'" % plat
940 if compiler is not None:
941 msg = msg + " with '%s' compiler" % compiler
942 raise DistutilsPlatformError, msg
Fred Drakeb94b8492001-12-06 20:51:35 +0000943
Greg Ward802d6b71999-09-29 12:20:55 +0000944 try:
945 module_name = "distutils." + module_name
946 __import__ (module_name)
947 module = sys.modules[module_name]
948 klass = vars(module)[class_name]
949 except ImportError:
950 raise DistutilsModuleError, \
951 "can't compile C/C++ code: unable to load module '%s'" % \
952 module_name
953 except KeyError:
954 raise DistutilsModuleError, \
955 ("can't compile C/C++ code: unable to find class '%s' " +
956 "in module '%s'") % (class_name, module_name)
957
Jeremy Hyltoncd8a1142002-06-04 20:14:43 +0000958 # XXX The None is necessary to preserve backwards compatibility
959 # with classes that expect verbose to be the first positional
960 # argument.
961 return klass (None, dry_run, force)
Greg Wardf7a39ec1999-09-08 02:29:08 +0000962
963
Greg Ward0bdd90a1999-12-12 17:19:58 +0000964def gen_preprocess_options (macros, include_dirs):
Greg Wardc3a43b42000-06-24 18:10:48 +0000965 """Generate C pre-processor options (-D, -U, -I) as used by at least
966 two types of compilers: the typical Unix compiler and Visual C++.
967 'macros' is the usual thing, a list of 1- or 2-tuples, where (name,)
968 means undefine (-U) macro 'name', and (name,value) means define (-D)
969 macro 'name' to 'value'. 'include_dirs' is just a list of directory
970 names to be added to the header file search path (-I). Returns a list
971 of command-line options suitable for either Unix compilers or Visual
972 C++.
973 """
Greg Wardf7a39ec1999-09-08 02:29:08 +0000974 # XXX it would be nice (mainly aesthetic, and so we don't generate
975 # stupid-looking command lines) to go over 'macros' and eliminate
976 # redundant definitions/undefinitions (ie. ensure that only the
977 # latest mention of a particular macro winds up on the command
978 # line). I don't think it's essential, though, since most (all?)
979 # Unix C compilers only pay attention to the latest -D or -U
980 # mention of a macro on their command line. Similar situation for
Greg Ward0bdd90a1999-12-12 17:19:58 +0000981 # 'include_dirs'. I'm punting on both for now. Anyways, weeding out
Greg Wardf7a39ec1999-09-08 02:29:08 +0000982 # redundancies like this should probably be the province of
983 # CCompiler, since the data structures used are inherited from it
984 # and therefore common to all CCompiler classes.
985
986 pp_opts = []
987 for macro in macros:
Greg Wardfbf8aff1999-09-21 18:35:09 +0000988
989 if not (type (macro) is TupleType and
990 1 <= len (macro) <= 2):
991 raise TypeError, \
992 ("bad macro definition '%s': " +
993 "each element of 'macros' list must be a 1- or 2-tuple") % \
994 macro
995
Greg Wardf7a39ec1999-09-08 02:29:08 +0000996 if len (macro) == 1: # undefine this macro
997 pp_opts.append ("-U%s" % macro[0])
998 elif len (macro) == 2:
999 if macro[1] is None: # define with no explicit value
1000 pp_opts.append ("-D%s" % macro[0])
1001 else:
1002 # XXX *don't* need to be clever about quoting the
1003 # macro value here, because we're going to avoid the
1004 # shell at all costs when we spawn the command!
1005 pp_opts.append ("-D%s=%s" % macro)
1006
Greg Ward0bdd90a1999-12-12 17:19:58 +00001007 for dir in include_dirs:
Greg Wardf7a39ec1999-09-08 02:29:08 +00001008 pp_opts.append ("-I%s" % dir)
1009
1010 return pp_opts
1011
1012# gen_preprocess_options ()
1013
1014
Greg Wardd03f88a2000-03-18 15:19:51 +00001015def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
Greg Wardf7a39ec1999-09-08 02:29:08 +00001016 """Generate linker options for searching library directories and
Greg Wardc3a43b42000-06-24 18:10:48 +00001017 linking with specific libraries. 'libraries' and 'library_dirs' are,
1018 respectively, lists of library names (not filenames!) and search
1019 directories. Returns a list of command-line options suitable for use
1020 with some compiler (depending on the two format strings passed in).
1021 """
Greg Wardf7a39ec1999-09-08 02:29:08 +00001022 lib_opts = []
1023
1024 for dir in library_dirs:
Greg Ward3febd601999-10-03 20:41:02 +00001025 lib_opts.append (compiler.library_dir_option (dir))
Greg Wardf7a39ec1999-09-08 02:29:08 +00001026
Greg Wardd03f88a2000-03-18 15:19:51 +00001027 for dir in runtime_library_dirs:
1028 lib_opts.append (compiler.runtime_library_dir_option (dir))
1029
Greg Wardf7a39ec1999-09-08 02:29:08 +00001030 # XXX it's important that we *not* remove redundant library mentions!
1031 # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
1032 # resolve all symbols. I just hope we never have to say "-lfoo obj.o
1033 # -lbar" to get things to work -- that's certainly a possibility, but a
1034 # pretty nasty way to arrange your C code.
1035
1036 for lib in libraries:
Greg Ward3febd601999-10-03 20:41:02 +00001037 (lib_dir, lib_name) = os.path.split (lib)
1038 if lib_dir:
1039 lib_file = compiler.find_library_file ([lib_dir], lib_name)
1040 if lib_file:
1041 lib_opts.append (lib_file)
1042 else:
1043 compiler.warn ("no library file corresponding to "
1044 "'%s' found (skipping)" % lib)
1045 else:
1046 lib_opts.append (compiler.library_option (lib))
Greg Wardf7a39ec1999-09-08 02:29:08 +00001047
1048 return lib_opts
1049
Greg Ward32c4a8a2000-03-06 03:40:29 +00001050# gen_lib_options ()