blob: 33caf86830cb90e69b856e8a55b93f20b949e4a0 [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
Greg Ward802d6b71999-09-29 12:20:55 +000010import sys, os
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 Ward32c4a8a2000-03-06 03:40:29 +000015from distutils.util import move_file, mkpath, newer_pairwise, newer_group
Greg Ward3f81cf71999-07-10 02:03:53 +000016
17
Greg Wardd1517112000-05-30 01:56:44 +000018# Exception classes used by the CCompiler implementation classes
19class CCompilerError (Exception):
20 """Failure doing some compile/link operation."""
21
22class CompileError (CCompilerError):
23 """Failure to compile one or more C/C++ source files."""
24
25class LibError (CCompilerError):
26 """Failure to create a static library from one or more C/C++ object
27 files."""
28
29class LinkError (CCompilerError):
30 """Failure to link one or more C/C++ object files into an executable
31 or shared library file."""
32
33
Greg Ward3f81cf71999-07-10 02:03:53 +000034class CCompiler:
35 """Abstract base class to define the interface that must be implemented
36 by real compiler abstraction classes. Might have some use as a
37 place for shared code, but it's not yet clear what code can be
38 shared between compiler abstraction models for different platforms.
39
40 The basic idea behind a compiler abstraction class is that each
41 instance can be used for all the compile/link steps in building
42 a single project. Thus, attributes common to all of those compile
43 and link steps -- include directories, macros to define, libraries
44 to link against, etc. -- are attributes of the compiler instance.
45 To allow for variability in how individual files are treated,
46 most (all?) of those attributes may be varied on a per-compilation
47 or per-link basis."""
48
Greg Ward802d6b71999-09-29 12:20:55 +000049 # 'compiler_type' is a class attribute that identifies this class. It
50 # keeps code that wants to know what kind of compiler it's dealing with
51 # from having to import all possible compiler classes just to do an
52 # 'isinstance'. In concrete CCompiler subclasses, 'compiler_type'
53 # should really, really be one of the keys of the 'compiler_class'
54 # dictionary (see below -- used by the 'new_compiler()' factory
55 # function) -- authors of new compiler interface classes are
56 # responsible for updating 'compiler_class'!
57 compiler_type = None
Greg Ward3f81cf71999-07-10 02:03:53 +000058
59 # XXX things not handled by this compiler abstraction model:
60 # * client can't provide additional options for a compiler,
61 # e.g. warning, optimization, debugging flags. Perhaps this
62 # should be the domain of concrete compiler abstraction classes
63 # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
64 # class should have methods for the common ones.
65 # * can't put output files (object files, libraries, whatever)
66 # into a separate directory from their inputs. Should this be
67 # handled by an 'output_dir' attribute of the whole object, or a
68 # parameter to the compile/link_* methods, or both?
69 # * can't completely override the include or library searchg
70 # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
Greg Warde1aaaa61999-08-14 23:50:50 +000071 # I'm not sure how widely supported this is even by Unix
Greg Ward3f81cf71999-07-10 02:03:53 +000072 # compilers, much less on other platforms. And I'm even less
Greg Warde1aaaa61999-08-14 23:50:50 +000073 # sure how useful it is; maybe for cross-compiling, but
74 # support for that is a ways off. (And anyways, cross
75 # compilers probably have a dedicated binary with the
76 # right paths compiled in. I hope.)
Greg Ward3f81cf71999-07-10 02:03:53 +000077 # * can't do really freaky things with the library list/library
78 # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
79 # different versions of libfoo.a in different locations. I
80 # think this is useless without the ability to null out the
81 # library search path anyways.
Greg Ward3f81cf71999-07-10 02:03:53 +000082
83
Greg Ward32c4a8a2000-03-06 03:40:29 +000084 # Subclasses that rely on the standard filename generation methods
85 # implemented below should override these; see the comment near
86 # those methods ('object_filenames()' et. al.) for details:
87 src_extensions = None # list of strings
88 obj_extension = None # string
89 static_lib_extension = None
90 shared_lib_extension = None # string
91 static_lib_format = None # format string
92 shared_lib_format = None # prob. same as static_lib_format
93 exe_extension = None # string
94
95
Greg Warde1aaaa61999-08-14 23:50:50 +000096 def __init__ (self,
97 verbose=0,
Greg Ward3febd601999-10-03 20:41:02 +000098 dry_run=0,
99 force=0):
Greg Warde1aaaa61999-08-14 23:50:50 +0000100
101 self.verbose = verbose
102 self.dry_run = dry_run
Greg Ward3febd601999-10-03 20:41:02 +0000103 self.force = force
Greg Ward3f81cf71999-07-10 02:03:53 +0000104
Greg Ward9b17cb51999-09-13 03:07:24 +0000105 # 'output_dir': a common output directory for object, library,
106 # shared object, and shared library files
107 self.output_dir = None
108
Greg Ward3f81cf71999-07-10 02:03:53 +0000109 # 'macros': a list of macro definitions (or undefinitions). A
110 # macro definition is a 2-tuple (name, value), where the value is
111 # either a string or None (no explicit value). A macro
112 # undefinition is a 1-tuple (name,).
113 self.macros = []
114
Greg Ward3f81cf71999-07-10 02:03:53 +0000115 # 'include_dirs': a list of directories to search for include files
116 self.include_dirs = []
117
118 # 'libraries': a list of libraries to include in any link
119 # (library names, not filenames: eg. "foo" not "libfoo.a")
120 self.libraries = []
121
122 # 'library_dirs': a list of directories to search for libraries
123 self.library_dirs = []
124
Greg Warde1aaaa61999-08-14 23:50:50 +0000125 # 'runtime_library_dirs': a list of directories to search for
126 # shared libraries/objects at runtime
127 self.runtime_library_dirs = []
128
Greg Ward3f81cf71999-07-10 02:03:53 +0000129 # 'objects': a list of object files (or similar, such as explicitly
130 # named library files) to include on any link
131 self.objects = []
132
133 # __init__ ()
134
135
136 def _find_macro (self, name):
137 i = 0
138 for defn in self.macros:
139 if defn[0] == name:
140 return i
141 i = i + 1
142
143 return None
144
145
146 def _check_macro_definitions (self, definitions):
147 """Ensures that every element of 'definitions' is a valid macro
148 definition, ie. either (name,value) 2-tuple or a (name,)
149 tuple. Do nothing if all definitions are OK, raise
150 TypeError otherwise."""
151
152 for defn in definitions:
153 if not (type (defn) is TupleType and
154 (len (defn) == 1 or
155 (len (defn) == 2 and
156 (type (defn[1]) is StringType or defn[1] is None))) and
157 type (defn[0]) is StringType):
158 raise TypeError, \
159 ("invalid macro definition '%s': " % defn) + \
160 "must be tuple (string,), (string, string), or " + \
161 "(string, None)"
162
163
164 # -- Bookkeeping methods -------------------------------------------
165
166 def define_macro (self, name, value=None):
167 """Define a preprocessor macro for all compilations driven by
168 this compiler object. The optional parameter 'value' should be
169 a string; if it is not supplied, then the macro will be defined
170 without an explicit value and the exact outcome depends on the
171 compiler used (XXX true? does ANSI say anything about this?)"""
172
173 # Delete from the list of macro definitions/undefinitions if
174 # already there (so that this one will take precedence).
175 i = self._find_macro (name)
176 if i is not None:
177 del self.macros[i]
178
179 defn = (name, value)
180 self.macros.append (defn)
181
182
183 def undefine_macro (self, name):
184 """Undefine a preprocessor macro for all compilations driven by
185 this compiler object. If the same macro is defined by
186 'define_macro()' and undefined by 'undefine_macro()' the last
187 call takes precedence (including multiple redefinitions or
188 undefinitions). If the macro is redefined/undefined on a
189 per-compilation basis (ie. in the call to 'compile()'), then
190 that takes precedence."""
191
192 # Delete from the list of macro definitions/undefinitions if
193 # already there (so that this one will take precedence).
194 i = self._find_macro (name)
195 if i is not None:
196 del self.macros[i]
197
198 undefn = (name,)
199 self.macros.append (undefn)
200
201
202 def add_include_dir (self, dir):
203 """Add 'dir' to the list of directories that will be searched
204 for header files. The compiler is instructed to search
205 directories in the order in which they are supplied by
206 successive calls to 'add_include_dir()'."""
207 self.include_dirs.append (dir)
208
209 def set_include_dirs (self, dirs):
210 """Set the list of directories that will be searched to 'dirs'
211 (a list of strings). Overrides any preceding calls to
212 'add_include_dir()'; subsequence calls to 'add_include_dir()'
213 add to the list passed to 'set_include_dirs()'. This does
214 not affect any list of standard include directories that
215 the compiler may search by default."""
216 self.include_dirs = copy (dirs)
217
218
219 def add_library (self, libname):
220 """Add 'libname' to the list of libraries that will be included
221 in all links driven by this compiler object. Note that
222 'libname' should *not* be the name of a file containing a
223 library, but the name of the library itself: the actual filename
224 will be inferred by the linker, the compiler, or the compiler
225 abstraction class (depending on the platform).
226
227 The linker will be instructed to link against libraries in the
228 order they were supplied to 'add_library()' and/or
229 'set_libraries()'. It is perfectly valid to duplicate library
230 names; the linker will be instructed to link against libraries
231 as many times as they are mentioned."""
232 self.libraries.append (libname)
233
234 def set_libraries (self, libnames):
235 """Set the list of libraries to be included in all links driven
236 by this compiler object to 'libnames' (a list of strings).
237 This does not affect any standard system libraries that the
238 linker may include by default."""
239
240 self.libraries = copy (libnames)
241
242
243 def add_library_dir (self, dir):
244 """Add 'dir' to the list of directories that will be searched for
245 libraries specified to 'add_library()' and 'set_libraries()'.
246 The linker will be instructed to search for libraries in the
247 order they are supplied to 'add_library_dir()' and/or
248 'set_library_dirs()'."""
249 self.library_dirs.append (dir)
250
251 def set_library_dirs (self, dirs):
252 """Set the list of library search directories to 'dirs' (a list
253 of strings). This does not affect any standard library
254 search path that the linker may search by default."""
255 self.library_dirs = copy (dirs)
256
257
Greg Warde1aaaa61999-08-14 23:50:50 +0000258 def add_runtime_library_dir (self, dir):
259 """Add 'dir' to the list of directories that will be searched for
260 shared libraries at runtime."""
261 self.runtime_library_dirs.append (dir)
262
263 def set_runtime_library_dirs (self, dirs):
264 """Set the list of directories to search for shared libraries
265 at runtime to 'dirs' (a list of strings). This does not affect
266 any standard search path that the runtime linker may search by
267 default."""
268 self.runtime_library_dirs = copy (dirs)
269
270
Greg Ward3f81cf71999-07-10 02:03:53 +0000271 def add_link_object (self, object):
272 """Add 'object' to the list of object files (or analogues, such
273 as explictly named library files or the output of "resource
274 compilers") to be included in every link driven by this
275 compiler object."""
276 self.objects.append (object)
277
278 def set_link_objects (self, objects):
279 """Set the list of object files (or analogues) to be included
280 in every link to 'objects'. This does not affect any
281 standard object files that the linker may include by default
282 (such as system libraries)."""
283 self.objects = copy (objects)
284
285
Greg Ward32c4a8a2000-03-06 03:40:29 +0000286 # -- Priviate utility methods --------------------------------------
287 # (here for the convenience of subclasses)
288
289 def _fix_compile_args (self, output_dir, macros, include_dirs):
290 """Typecheck and fix-up some of the arguments to the 'compile()' method,
291 and return fixed-up values. Specifically: if 'output_dir' is
292 None, replaces it with 'self.output_dir'; ensures that 'macros'
293 is a list, and augments it with 'self.macros'; ensures that
294 'include_dirs' is a list, and augments it with
295 'self.include_dirs'. Guarantees that the returned values are of
296 the correct type, i.e. for 'output_dir' either string or None,
297 and for 'macros' and 'include_dirs' either list or None."""
298
299 if output_dir is None:
300 output_dir = self.output_dir
301 elif type (output_dir) is not StringType:
302 raise TypeError, "'output_dir' must be a string or None"
303
304 if macros is None:
305 macros = self.macros
306 elif type (macros) is ListType:
307 macros = macros + (self.macros or [])
308 else:
309 raise TypeError, \
310 "'macros' (if supplied) must be a list of tuples"
311
312 if include_dirs is None:
313 include_dirs = self.include_dirs
314 elif type (include_dirs) in (ListType, TupleType):
315 include_dirs = list (include_dirs) + (self.include_dirs or [])
316 else:
317 raise TypeError, \
318 "'include_dirs' (if supplied) must be a list of strings"
319
320 return (output_dir, macros, include_dirs)
321
322 # _fix_compile_args ()
323
324
325 def _prep_compile (self, sources, output_dir):
326 """Determine the list of object files corresponding to 'sources', and
327 figure out which ones really need to be recompiled. Return a list
328 of all object files and a dictionary telling which source files can
329 be skipped."""
330
331 # Get the list of expected output (object) files
332 objects = self.object_filenames (sources,
333 output_dir=output_dir)
334
335 if self.force:
336 skip_source = {} # rebuild everything
337 for source in sources:
338 skip_source[source] = 0
339 else:
340 # Figure out which source files we have to recompile according
341 # to a simplistic check -- we just compare the source and
342 # object file, no deep dependency checking involving header
343 # files.
344 skip_source = {} # rebuild everything
345 for source in sources: # no wait, rebuild nothing
346 skip_source[source] = 1
347
348 (n_sources, n_objects) = newer_pairwise (sources, objects)
349 for source in n_sources: # no really, only rebuild what's out-of-date
350 skip_source[source] = 0
351
352 return (objects, skip_source)
353
354 # _prep_compile ()
355
356
Greg Wardf10f95d2000-03-26 21:37:09 +0000357 def _fix_object_args (self, objects, output_dir):
358 """Typecheck and fix up some arguments supplied to various
359 methods. Specifically: ensure that 'objects' is a list; if
360 output_dir is None, replace with self.output_dir. Return fixed
361 versions of 'objects' and 'output_dir'."""
Greg Ward32c4a8a2000-03-06 03:40:29 +0000362
363 if type (objects) not in (ListType, TupleType):
364 raise TypeError, \
365 "'objects' must be a list or tuple of strings"
366 objects = list (objects)
367
368 if output_dir is None:
369 output_dir = self.output_dir
370 elif type (output_dir) is not StringType:
371 raise TypeError, "'output_dir' must be a string or None"
372
Greg Wardf10f95d2000-03-26 21:37:09 +0000373 return (objects, output_dir)
Greg Ward32c4a8a2000-03-06 03:40:29 +0000374
Greg Ward32c4a8a2000-03-06 03:40:29 +0000375
Greg Wardf10f95d2000-03-26 21:37:09 +0000376 def _fix_lib_args (self, libraries, library_dirs, runtime_library_dirs):
377 """Typecheck and fix up some of the arguments supplied to the
378 'link_*' methods. Specifically: ensure that all arguments are
379 lists, and augment them with their permanent versions
380 (eg. 'self.libraries' augments 'libraries'). Return a tuple
381 with fixed versions of all arguments."""
382
383 if libraries is None:
384 libraries = self.libraries
385 elif type (libraries) in (ListType, TupleType):
386 libraries = list (libraries) + (self.libraries or [])
Greg Ward32c4a8a2000-03-06 03:40:29 +0000387 else:
Greg Wardf10f95d2000-03-26 21:37:09 +0000388 raise TypeError, \
389 "'libraries' (if supplied) must be a list of strings"
Greg Ward32c4a8a2000-03-06 03:40:29 +0000390
Greg Wardf10f95d2000-03-26 21:37:09 +0000391 if library_dirs is None:
392 library_dirs = self.library_dirs
393 elif type (library_dirs) in (ListType, TupleType):
394 library_dirs = list (library_dirs) + (self.library_dirs or [])
395 else:
396 raise TypeError, \
397 "'library_dirs' (if supplied) must be a list of strings"
398
399 if runtime_library_dirs is None:
400 runtime_library_dirs = self.runtime_library_dirs
401 elif type (runtime_library_dirs) in (ListType, TupleType):
402 runtime_library_dirs = (list (runtime_library_dirs) +
403 (self.runtime_library_dirs or []))
404 else:
405 raise TypeError, \
406 "'runtime_library_dirs' (if supplied) " + \
407 "must be a list of strings"
408
409 return (libraries, library_dirs, runtime_library_dirs)
410
411 # _fix_lib_args ()
Greg Ward32c4a8a2000-03-06 03:40:29 +0000412
413
414 def _need_link (self, objects, output_file):
415 """Return true if we need to relink the files listed in 'objects' to
416 recreate 'output_file'."""
417
418 if self.force:
419 return 1
420 else:
421 if self.dry_run:
422 newer = newer_group (objects, output_file, missing='newer')
423 else:
424 newer = newer_group (objects, output_file)
425 return newer
426
427 # _need_link ()
428
429
Greg Ward3f81cf71999-07-10 02:03:53 +0000430 # -- Worker methods ------------------------------------------------
431 # (must be implemented by subclasses)
432
433 def compile (self,
434 sources,
Greg Ward9b17cb51999-09-13 03:07:24 +0000435 output_dir=None,
Greg Ward3f81cf71999-07-10 02:03:53 +0000436 macros=None,
Greg Ward0bdd90a1999-12-12 17:19:58 +0000437 include_dirs=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000438 debug=0,
Greg Ward802d6b71999-09-29 12:20:55 +0000439 extra_preargs=None,
440 extra_postargs=None):
Greg Ward3f81cf71999-07-10 02:03:53 +0000441 """Compile one or more C/C++ source files. 'sources' must be
442 a list of strings, each one the name of a C/C++ source
Greg Ward32c4a8a2000-03-06 03:40:29 +0000443 file. Return a list of object filenames, one per source
444 filename in 'sources'. Depending on the implementation,
445 not all source files will necessarily be compiled, but
446 all corresponding object filenames will be returned.
447
448 If 'output_dir' is given, object files will be put under it,
449 while retaining their original path component. That is,
450 "foo/bar.c" normally compiles to "foo/bar.o" (for a Unix
451 implementation); if 'output_dir' is "build", then it would
452 compile to "build/foo/bar.o".
Greg Ward3f81cf71999-07-10 02:03:53 +0000453
454 'macros', if given, must be a list of macro definitions. A
455 macro definition is either a (name, value) 2-tuple or a (name,)
456 1-tuple. The former defines a macro; if the value is None, the
457 macro is defined without an explicit value. The 1-tuple case
458 undefines a macro. Later definitions/redefinitions/
459 undefinitions take precedence.
460
Greg Ward3c045a52000-02-09 02:16:14 +0000461 'include_dirs', if given, must be a list of strings, the
462 directories to add to the default include file search path for
463 this compilation only.
464
465 'debug' is a boolean; if true, the compiler will be instructed
466 to output debug symbols in (or alongside) the object file(s).
Greg Ward802d6b71999-09-29 12:20:55 +0000467
Greg Ward32c4a8a2000-03-06 03:40:29 +0000468 'extra_preargs' and 'extra_postargs' are implementation-
469 dependent. On platforms that have the notion of a command-line
470 (e.g. Unix, DOS/Windows), they are most likely lists of strings:
471 extra command-line arguments to prepand/append to the compiler
472 command line. On other platforms, consult the implementation
473 class documentation. In any event, they are intended as an
Greg Ward802d6b71999-09-29 12:20:55 +0000474 escape hatch for those occasions when the abstract compiler
Greg Wardd1517112000-05-30 01:56:44 +0000475 framework doesn't cut the mustard.
476
477 Raises CompileError on failure."""
Greg Ward802d6b71999-09-29 12:20:55 +0000478
Greg Ward3f81cf71999-07-10 02:03:53 +0000479 pass
480
481
Greg Ward036c8052000-03-10 01:48:32 +0000482 def create_static_lib (self,
483 objects,
484 output_libname,
485 output_dir=None,
486 debug=0):
Greg Ward3f81cf71999-07-10 02:03:53 +0000487 """Link a bunch of stuff together to create a static library
488 file. The "bunch of stuff" consists of the list of object
489 files supplied as 'objects', the extra object files supplied
490 to 'add_link_object()' and/or 'set_link_objects()', the
491 libraries supplied to 'add_library()' and/or
492 'set_libraries()', and the libraries supplied as 'libraries'
493 (if any).
494
Greg Ward3c045a52000-02-09 02:16:14 +0000495 'output_libname' should be a library name, not a filename; the
496 filename will be inferred from the library name. 'output_dir'
497 is the directory where the library file will be put.
498
499 'debug' is a boolean; if true, debugging information will be
500 included in the library (note that on most platforms, it is the
501 compile step where this matters: the 'debug' flag is included
Greg Wardd1517112000-05-30 01:56:44 +0000502 here just for consistency).
503
504 Raises LibError on failure."""
Greg Ward3c045a52000-02-09 02:16:14 +0000505
506 pass
507
508
509 def link_shared_lib (self,
510 objects,
511 output_libname,
512 output_dir=None,
513 libraries=None,
514 library_dirs=None,
Greg Wardf10f95d2000-03-26 21:37:09 +0000515 runtime_library_dirs=None,
Greg Ward5299b6a2000-05-20 13:23:21 +0000516 export_symbols=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000517 debug=0,
518 extra_preargs=None,
519 extra_postargs=None):
520 """Link a bunch of stuff together to create a shared library
Greg Ward036c8052000-03-10 01:48:32 +0000521 file. Similar semantics to 'create_static_lib()', with the
522 addition of other libraries to link against and directories to
523 search for them. Also, of course, the type and name of
524 the generated file will almost certainly be different, as will
525 the program used to create it.
Greg Ward3f81cf71999-07-10 02:03:53 +0000526
Greg Ward3febd601999-10-03 20:41:02 +0000527 'libraries' is a list of libraries to link against. These are
528 library names, not filenames, since they're translated into
529 filenames in a platform-specific way (eg. "foo" becomes
530 "libfoo.a" on Unix and "foo.lib" on DOS/Windows). However, they
531 can include a directory component, which means the linker will
532 look in that specific directory rather than searching all the
533 normal locations.
534
535 'library_dirs', if supplied, should be a list of directories to
536 search for libraries that were specified as bare library names
537 (ie. no directory component). These are on top of the system
538 default and those supplied to 'add_library_dir()' and/or
Greg Ward5299b6a2000-05-20 13:23:21 +0000539 'set_library_dirs()'. 'runtime_library_dirs' is a list of
540 directories that will be embedded into the shared library and
541 used to search for other shared libraries that *it* depends on
542 at run-time. (This may only be relevant on Unix.)
543
544 'export_symbols' is a list of symbols that the shared library
545 will export. (This appears to be relevant only on Windows.)
Greg Ward802d6b71999-09-29 12:20:55 +0000546
Greg Ward036c8052000-03-10 01:48:32 +0000547 'debug' is as for 'compile()' and 'create_static_lib()', with the
Greg Ward3c045a52000-02-09 02:16:14 +0000548 slight distinction that it actually matters on most platforms
Greg Ward036c8052000-03-10 01:48:32 +0000549 (as opposed to 'create_static_lib()', which includes a 'debug'
Greg Ward3c045a52000-02-09 02:16:14 +0000550 flag mostly for form's sake).
551
Greg Ward802d6b71999-09-29 12:20:55 +0000552 'extra_preargs' and 'extra_postargs' are as for 'compile()'
553 (except of course that they supply command-line arguments
Greg Wardd1517112000-05-30 01:56:44 +0000554 for the particular linker being used).
555
556 Raises LinkError on failure."""
Greg Ward3f81cf71999-07-10 02:03:53 +0000557
558 pass
559
560
Greg Ward3f81cf71999-07-10 02:03:53 +0000561 def link_shared_object (self,
562 objects,
563 output_filename,
Greg Ward9b17cb51999-09-13 03:07:24 +0000564 output_dir=None,
Greg Ward3f81cf71999-07-10 02:03:53 +0000565 libraries=None,
Greg Ward26e48ea1999-08-29 18:17:36 +0000566 library_dirs=None,
Greg Wardf10f95d2000-03-26 21:37:09 +0000567 runtime_library_dirs=None,
Greg Ward5299b6a2000-05-20 13:23:21 +0000568 export_symbols=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000569 debug=0,
Greg Ward802d6b71999-09-29 12:20:55 +0000570 extra_preargs=None,
571 extra_postargs=None):
Greg Ward3f81cf71999-07-10 02:03:53 +0000572 """Link a bunch of stuff together to create a shared object
Greg Ward9b17cb51999-09-13 03:07:24 +0000573 file. Much like 'link_shared_lib()', except the output filename
574 is explicitly supplied as 'output_filename'. If 'output_dir' is
575 supplied, 'output_filename' is relative to it
Greg Ward802d6b71999-09-29 12:20:55 +0000576 (i.e. 'output_filename' can provide directory components if
Greg Wardd1517112000-05-30 01:56:44 +0000577 needed).
578
579 Raises LinkError on failure."""
Greg Ward3f81cf71999-07-10 02:03:53 +0000580 pass
581
Greg Warde1aaaa61999-08-14 23:50:50 +0000582
Greg Ward5baf1c22000-01-09 22:41:02 +0000583 def link_executable (self,
584 objects,
585 output_progname,
586 output_dir=None,
587 libraries=None,
588 library_dirs=None,
Greg Wardf10f95d2000-03-26 21:37:09 +0000589 runtime_library_dirs=None,
Greg Ward3c045a52000-02-09 02:16:14 +0000590 debug=0,
Greg Ward5baf1c22000-01-09 22:41:02 +0000591 extra_preargs=None,
592 extra_postargs=None):
593 """Link a bunch of stuff together to create a binary executable
Greg Ward036c8052000-03-10 01:48:32 +0000594 file. The "bunch of stuff" is as for 'link_shared_lib()'.
Greg Ward5baf1c22000-01-09 22:41:02 +0000595 'output_progname' should be the base name of the executable
596 program--e.g. on Unix the same as the output filename, but
Greg Wardd1517112000-05-30 01:56:44 +0000597 on DOS/Windows ".exe" will be appended.
598
599 Raises LinkError on failure."""
Greg Ward5baf1c22000-01-09 22:41:02 +0000600 pass
601
602
603
Greg Wardf7edea72000-05-20 13:31:32 +0000604 # -- Miscellaneous methods -----------------------------------------
605 # These are all used by the 'gen_lib_options() function; there is
606 # no appropriate default implementation so subclasses should
607 # implement all of these.
608
609 def library_dir_option (self, dir):
610 """Return the compiler option to add 'dir' to the list of directories
611 searched for libraries."""
612 raise NotImplementedError
613
614 def runtime_library_dir_option (self, dir):
615 """Return the compiler option to add 'dir' to the list of directories
616 searched for runtime libraries."""
617 raise NotImplementedError
618
619 def library_option (self, lib):
620 """Return the compiler option to add 'dir' to the list of libraries
621 linked into the shared library or executable."""
622 raise NotImplementedError
623
624 def find_library_file (self, dirs, lib):
625 """Search the specified list of directories for a static or shared
626 library file 'lib' and return the full path to that file. Return
627 None if it wasn't found in any of the specified directories."""
628 raise NotImplementedError
629
630
Greg Ward32c4a8a2000-03-06 03:40:29 +0000631 # -- Filename generation methods -----------------------------------
Greg Warde1aaaa61999-08-14 23:50:50 +0000632
Greg Ward32c4a8a2000-03-06 03:40:29 +0000633 # The default implementation of the filename generating methods are
634 # prejudiced towards the Unix/DOS/Windows view of the world:
635 # * object files are named by replacing the source file extension
636 # (eg. .c/.cpp -> .o/.obj)
637 # * library files (shared or static) are named by plugging the
638 # library name and extension into a format string, eg.
639 # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
640 # * executables are named by appending an extension (possibly
641 # empty) to the program name: eg. progname + ".exe" for
642 # Windows
643 #
644 # To reduce redundant code, these methods expect to find
645 # several attributes in the current object (presumably defined
646 # as class attributes):
647 # * src_extensions -
648 # list of C/C++ source file extensions, eg. ['.c', '.cpp']
649 # * obj_extension -
650 # object file extension, eg. '.o' or '.obj'
651 # * static_lib_extension -
652 # extension for static library files, eg. '.a' or '.lib'
653 # * shared_lib_extension -
654 # extension for shared library/object files, eg. '.so', '.dll'
655 # * static_lib_format -
656 # format string for generating static library filenames,
657 # eg. 'lib%s.%s' or '%s.%s'
658 # * shared_lib_format
659 # format string for generating shared library filenames
660 # (probably same as static_lib_format, since the extension
661 # is one of the intended parameters to the format string)
662 # * exe_extension -
663 # extension for executable files, eg. '' or '.exe'
Greg Ward9b17cb51999-09-13 03:07:24 +0000664
Greg Ward32c4a8a2000-03-06 03:40:29 +0000665 def object_filenames (self,
666 source_filenames,
667 strip_dir=0,
668 output_dir=''):
669 if output_dir is None: output_dir = ''
670 obj_names = []
671 for src_name in source_filenames:
672 (base, ext) = os.path.splitext (src_name)
673 if ext not in self.src_extensions:
674 continue
675 if strip_dir:
676 base = os.path.basename (base)
677 obj_names.append (os.path.join (output_dir,
678 base + self.obj_extension))
679 return obj_names
Greg Warde1aaaa61999-08-14 23:50:50 +0000680
Greg Ward32c4a8a2000-03-06 03:40:29 +0000681 # object_filenames ()
Greg Warde1aaaa61999-08-14 23:50:50 +0000682
Greg Warde1aaaa61999-08-14 23:50:50 +0000683
Greg Ward32c4a8a2000-03-06 03:40:29 +0000684 def shared_object_filename (self,
685 basename,
686 strip_dir=0,
687 output_dir=''):
688 if output_dir is None: output_dir = ''
689 if strip_dir:
690 basename = os.path.basename (basename)
691 return os.path.join (output_dir, basename + self.shared_lib_extension)
Greg Warde1aaaa61999-08-14 23:50:50 +0000692
Greg Ward26e48ea1999-08-29 18:17:36 +0000693
Greg Ward32c4a8a2000-03-06 03:40:29 +0000694 def library_filename (self,
695 libname,
696 lib_type='static', # or 'shared'
697 strip_dir=0,
698 output_dir=''):
699
700 if output_dir is None: output_dir = ''
701 if lib_type not in ("static","shared"):
702 raise ValueError, "'lib_type' must be \"static\" or \"shared\""
703 fmt = getattr (self, lib_type + "_lib_format")
704 ext = getattr (self, lib_type + "_lib_extension")
705
706 (dir, base) = os.path.split (libname)
707 filename = fmt % (base, ext)
708 if strip_dir:
709 dir = ''
710
711 return os.path.join (output_dir, dir, filename)
712
Greg Warde1aaaa61999-08-14 23:50:50 +0000713
714 # -- Utility methods -----------------------------------------------
715
Greg Ward9b17cb51999-09-13 03:07:24 +0000716 def announce (self, msg, level=1):
717 if self.verbose >= level:
718 print msg
719
Greg Ward3febd601999-10-03 20:41:02 +0000720 def warn (self, msg):
721 sys.stderr.write ("warning: %s\n" % msg)
722
Greg Warde1aaaa61999-08-14 23:50:50 +0000723 def spawn (self, cmd):
724 spawn (cmd, verbose=self.verbose, dry_run=self.dry_run)
725
Greg Ward9b17cb51999-09-13 03:07:24 +0000726 def move_file (self, src, dst):
727 return move_file (src, dst, verbose=self.verbose, dry_run=self.dry_run)
728
Greg Ward013f0c82000-03-01 14:43:12 +0000729 def mkpath (self, name, mode=0777):
730 mkpath (name, mode, self.verbose, self.dry_run)
731
Greg Warde1aaaa61999-08-14 23:50:50 +0000732
Greg Ward3f81cf71999-07-10 02:03:53 +0000733# class CCompiler
734
735
Greg Ward802d6b71999-09-29 12:20:55 +0000736# Map a platform ('posix', 'nt') to the default compiler type for
737# that platform.
738default_compiler = { 'posix': 'unix',
739 'nt': 'msvc',
740 }
741
742# Map compiler types to (module_name, class_name) pairs -- ie. where to
743# find the code that implements an interface to this compiler. (The module
744# is assumed to be in the 'distutils' package.)
745compiler_class = { 'unix': ('unixccompiler', 'UnixCCompiler'),
746 'msvc': ('msvccompiler', 'MSVCCompiler'),
747 }
748
749
Greg Warde1aaaa61999-08-14 23:50:50 +0000750def new_compiler (plat=None,
Greg Ward802d6b71999-09-29 12:20:55 +0000751 compiler=None,
Greg Warde1aaaa61999-08-14 23:50:50 +0000752 verbose=0,
Greg Ward3febd601999-10-03 20:41:02 +0000753 dry_run=0,
754 force=0):
Greg Ward3f81cf71999-07-10 02:03:53 +0000755
Greg Ward802d6b71999-09-29 12:20:55 +0000756 """Generate an instance of some CCompiler subclass for the supplied
757 platform/compiler combination. 'plat' defaults to 'os.name'
758 (eg. 'posix', 'nt'), and 'compiler' defaults to the default
759 compiler for that platform. Currently only 'posix' and 'nt'
760 are supported, and the default compilers are "traditional Unix
761 interface" (UnixCCompiler class) and Visual C++ (MSVCCompiler
762 class). Note that it's perfectly possible to ask for a Unix
763 compiler object under Windows, and a Microsoft compiler object
764 under Unix -- if you supply a value for 'compiler', 'plat'
765 is ignored."""
766
767 if plat is None:
768 plat = os.name
769
770 try:
771 if compiler is None:
772 compiler = default_compiler[plat]
773
774 (module_name, class_name) = compiler_class[compiler]
775 except KeyError:
776 msg = "don't know how to compile C/C++ code on platform '%s'" % plat
777 if compiler is not None:
778 msg = msg + " with '%s' compiler" % compiler
779 raise DistutilsPlatformError, msg
780
781 try:
782 module_name = "distutils." + module_name
783 __import__ (module_name)
784 module = sys.modules[module_name]
785 klass = vars(module)[class_name]
786 except ImportError:
787 raise DistutilsModuleError, \
788 "can't compile C/C++ code: unable to load module '%s'" % \
789 module_name
790 except KeyError:
791 raise DistutilsModuleError, \
792 ("can't compile C/C++ code: unable to find class '%s' " +
793 "in module '%s'") % (class_name, module_name)
794
Greg Ward3febd601999-10-03 20:41:02 +0000795 return klass (verbose, dry_run, force)
Greg Wardf7a39ec1999-09-08 02:29:08 +0000796
797
Greg Ward0bdd90a1999-12-12 17:19:58 +0000798def gen_preprocess_options (macros, include_dirs):
Greg Wardf7a39ec1999-09-08 02:29:08 +0000799 """Generate C pre-processor options (-D, -U, -I) as used by at
800 least two types of compilers: the typical Unix compiler and Visual
801 C++. 'macros' is the usual thing, a list of 1- or 2-tuples, where
802 (name,) means undefine (-U) macro 'name', and (name,value) means
Greg Ward0bdd90a1999-12-12 17:19:58 +0000803 define (-D) macro 'name' to 'value'. 'include_dirs' is just a list of
Greg Wardf7a39ec1999-09-08 02:29:08 +0000804 directory names to be added to the header file search path (-I).
805 Returns a list of command-line options suitable for either
806 Unix compilers or Visual C++."""
807
808 # XXX it would be nice (mainly aesthetic, and so we don't generate
809 # stupid-looking command lines) to go over 'macros' and eliminate
810 # redundant definitions/undefinitions (ie. ensure that only the
811 # latest mention of a particular macro winds up on the command
812 # line). I don't think it's essential, though, since most (all?)
813 # Unix C compilers only pay attention to the latest -D or -U
814 # mention of a macro on their command line. Similar situation for
Greg Ward0bdd90a1999-12-12 17:19:58 +0000815 # 'include_dirs'. I'm punting on both for now. Anyways, weeding out
Greg Wardf7a39ec1999-09-08 02:29:08 +0000816 # redundancies like this should probably be the province of
817 # CCompiler, since the data structures used are inherited from it
818 # and therefore common to all CCompiler classes.
819
820 pp_opts = []
821 for macro in macros:
Greg Wardfbf8aff1999-09-21 18:35:09 +0000822
823 if not (type (macro) is TupleType and
824 1 <= len (macro) <= 2):
825 raise TypeError, \
826 ("bad macro definition '%s': " +
827 "each element of 'macros' list must be a 1- or 2-tuple") % \
828 macro
829
Greg Wardf7a39ec1999-09-08 02:29:08 +0000830 if len (macro) == 1: # undefine this macro
831 pp_opts.append ("-U%s" % macro[0])
832 elif len (macro) == 2:
833 if macro[1] is None: # define with no explicit value
834 pp_opts.append ("-D%s" % macro[0])
835 else:
836 # XXX *don't* need to be clever about quoting the
837 # macro value here, because we're going to avoid the
838 # shell at all costs when we spawn the command!
839 pp_opts.append ("-D%s=%s" % macro)
840
Greg Ward0bdd90a1999-12-12 17:19:58 +0000841 for dir in include_dirs:
Greg Wardf7a39ec1999-09-08 02:29:08 +0000842 pp_opts.append ("-I%s" % dir)
843
844 return pp_opts
845
846# gen_preprocess_options ()
847
848
Greg Wardd03f88a2000-03-18 15:19:51 +0000849def gen_lib_options (compiler, library_dirs, runtime_library_dirs, libraries):
Greg Wardf7a39ec1999-09-08 02:29:08 +0000850 """Generate linker options for searching library directories and
851 linking with specific libraries. 'libraries' and 'library_dirs'
852 are, respectively, lists of library names (not filenames!) and
Greg Ward3febd601999-10-03 20:41:02 +0000853 search directories. Returns a list of command-line options suitable
854 for use with some compiler (depending on the two format strings
855 passed in)."""
Greg Wardf7a39ec1999-09-08 02:29:08 +0000856
857 lib_opts = []
858
859 for dir in library_dirs:
Greg Ward3febd601999-10-03 20:41:02 +0000860 lib_opts.append (compiler.library_dir_option (dir))
Greg Wardf7a39ec1999-09-08 02:29:08 +0000861
Greg Wardd03f88a2000-03-18 15:19:51 +0000862 for dir in runtime_library_dirs:
863 lib_opts.append (compiler.runtime_library_dir_option (dir))
864
Greg Wardf7a39ec1999-09-08 02:29:08 +0000865 # XXX it's important that we *not* remove redundant library mentions!
866 # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
867 # resolve all symbols. I just hope we never have to say "-lfoo obj.o
868 # -lbar" to get things to work -- that's certainly a possibility, but a
869 # pretty nasty way to arrange your C code.
870
871 for lib in libraries:
Greg Ward3febd601999-10-03 20:41:02 +0000872 (lib_dir, lib_name) = os.path.split (lib)
873 if lib_dir:
874 lib_file = compiler.find_library_file ([lib_dir], lib_name)
875 if lib_file:
876 lib_opts.append (lib_file)
877 else:
878 compiler.warn ("no library file corresponding to "
879 "'%s' found (skipping)" % lib)
880 else:
881 lib_opts.append (compiler.library_option (lib))
Greg Wardf7a39ec1999-09-08 02:29:08 +0000882
883 return lib_opts
884
Greg Ward32c4a8a2000-03-06 03:40:29 +0000885# gen_lib_options ()