blob: b1167ac25a3d484c9a167f2ca1445a40315f31ae [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
8__rcsid__ = "$Id$"
9
10import os
11from types import *
12from copy import copy
13from distutils.errors import *
Greg Warde1aaaa61999-08-14 23:50:50 +000014from distutils.spawn import spawn
Greg Ward3f81cf71999-07-10 02:03:53 +000015
16
17class CCompiler:
18 """Abstract base class to define the interface that must be implemented
19 by real compiler abstraction classes. Might have some use as a
20 place for shared code, but it's not yet clear what code can be
21 shared between compiler abstraction models for different platforms.
22
23 The basic idea behind a compiler abstraction class is that each
24 instance can be used for all the compile/link steps in building
25 a single project. Thus, attributes common to all of those compile
26 and link steps -- include directories, macros to define, libraries
27 to link against, etc. -- are attributes of the compiler instance.
28 To allow for variability in how individual files are treated,
29 most (all?) of those attributes may be varied on a per-compilation
30 or per-link basis."""
31
32
33 # XXX things not handled by this compiler abstraction model:
34 # * client can't provide additional options for a compiler,
35 # e.g. warning, optimization, debugging flags. Perhaps this
36 # should be the domain of concrete compiler abstraction classes
37 # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
38 # class should have methods for the common ones.
39 # * can't put output files (object files, libraries, whatever)
40 # into a separate directory from their inputs. Should this be
41 # handled by an 'output_dir' attribute of the whole object, or a
42 # parameter to the compile/link_* methods, or both?
43 # * can't completely override the include or library searchg
44 # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
Greg Warde1aaaa61999-08-14 23:50:50 +000045 # I'm not sure how widely supported this is even by Unix
Greg Ward3f81cf71999-07-10 02:03:53 +000046 # compilers, much less on other platforms. And I'm even less
Greg Warde1aaaa61999-08-14 23:50:50 +000047 # sure how useful it is; maybe for cross-compiling, but
48 # support for that is a ways off. (And anyways, cross
49 # compilers probably have a dedicated binary with the
50 # right paths compiled in. I hope.)
Greg Ward3f81cf71999-07-10 02:03:53 +000051 # * can't do really freaky things with the library list/library
52 # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
53 # different versions of libfoo.a in different locations. I
54 # think this is useless without the ability to null out the
55 # library search path anyways.
Greg Ward3f81cf71999-07-10 02:03:53 +000056
57
Greg Warde1aaaa61999-08-14 23:50:50 +000058 def __init__ (self,
59 verbose=0,
60 dry_run=0):
61
62 self.verbose = verbose
63 self.dry_run = dry_run
Greg Ward3f81cf71999-07-10 02:03:53 +000064
65 # 'macros': a list of macro definitions (or undefinitions). A
66 # macro definition is a 2-tuple (name, value), where the value is
67 # either a string or None (no explicit value). A macro
68 # undefinition is a 1-tuple (name,).
69 self.macros = []
70
Greg Ward3f81cf71999-07-10 02:03:53 +000071 # 'include_dirs': a list of directories to search for include files
72 self.include_dirs = []
73
74 # 'libraries': a list of libraries to include in any link
75 # (library names, not filenames: eg. "foo" not "libfoo.a")
76 self.libraries = []
77
78 # 'library_dirs': a list of directories to search for libraries
79 self.library_dirs = []
80
Greg Warde1aaaa61999-08-14 23:50:50 +000081 # 'runtime_library_dirs': a list of directories to search for
82 # shared libraries/objects at runtime
83 self.runtime_library_dirs = []
84
Greg Ward3f81cf71999-07-10 02:03:53 +000085 # 'objects': a list of object files (or similar, such as explicitly
86 # named library files) to include on any link
87 self.objects = []
88
89 # __init__ ()
90
91
92 def _find_macro (self, name):
93 i = 0
94 for defn in self.macros:
95 if defn[0] == name:
96 return i
97 i = i + 1
98
99 return None
100
101
102 def _check_macro_definitions (self, definitions):
103 """Ensures that every element of 'definitions' is a valid macro
104 definition, ie. either (name,value) 2-tuple or a (name,)
105 tuple. Do nothing if all definitions are OK, raise
106 TypeError otherwise."""
107
108 for defn in definitions:
109 if not (type (defn) is TupleType and
110 (len (defn) == 1 or
111 (len (defn) == 2 and
112 (type (defn[1]) is StringType or defn[1] is None))) and
113 type (defn[0]) is StringType):
114 raise TypeError, \
115 ("invalid macro definition '%s': " % defn) + \
116 "must be tuple (string,), (string, string), or " + \
117 "(string, None)"
118
119
120 # -- Bookkeeping methods -------------------------------------------
121
122 def define_macro (self, name, value=None):
123 """Define a preprocessor macro for all compilations driven by
124 this compiler object. The optional parameter 'value' should be
125 a string; if it is not supplied, then the macro will be defined
126 without an explicit value and the exact outcome depends on the
127 compiler used (XXX true? does ANSI say anything about this?)"""
128
129 # Delete from the list of macro definitions/undefinitions if
130 # already there (so that this one will take precedence).
131 i = self._find_macro (name)
132 if i is not None:
133 del self.macros[i]
134
135 defn = (name, value)
136 self.macros.append (defn)
137
138
139 def undefine_macro (self, name):
140 """Undefine a preprocessor macro for all compilations driven by
141 this compiler object. If the same macro is defined by
142 'define_macro()' and undefined by 'undefine_macro()' the last
143 call takes precedence (including multiple redefinitions or
144 undefinitions). If the macro is redefined/undefined on a
145 per-compilation basis (ie. in the call to 'compile()'), then
146 that takes precedence."""
147
148 # Delete from the list of macro definitions/undefinitions if
149 # already there (so that this one will take precedence).
150 i = self._find_macro (name)
151 if i is not None:
152 del self.macros[i]
153
154 undefn = (name,)
155 self.macros.append (undefn)
156
157
158 def add_include_dir (self, dir):
159 """Add 'dir' to the list of directories that will be searched
160 for header files. The compiler is instructed to search
161 directories in the order in which they are supplied by
162 successive calls to 'add_include_dir()'."""
163 self.include_dirs.append (dir)
164
165 def set_include_dirs (self, dirs):
166 """Set the list of directories that will be searched to 'dirs'
167 (a list of strings). Overrides any preceding calls to
168 'add_include_dir()'; subsequence calls to 'add_include_dir()'
169 add to the list passed to 'set_include_dirs()'. This does
170 not affect any list of standard include directories that
171 the compiler may search by default."""
172 self.include_dirs = copy (dirs)
173
174
175 def add_library (self, libname):
176 """Add 'libname' to the list of libraries that will be included
177 in all links driven by this compiler object. Note that
178 'libname' should *not* be the name of a file containing a
179 library, but the name of the library itself: the actual filename
180 will be inferred by the linker, the compiler, or the compiler
181 abstraction class (depending on the platform).
182
183 The linker will be instructed to link against libraries in the
184 order they were supplied to 'add_library()' and/or
185 'set_libraries()'. It is perfectly valid to duplicate library
186 names; the linker will be instructed to link against libraries
187 as many times as they are mentioned."""
188 self.libraries.append (libname)
189
190 def set_libraries (self, libnames):
191 """Set the list of libraries to be included in all links driven
192 by this compiler object to 'libnames' (a list of strings).
193 This does not affect any standard system libraries that the
194 linker may include by default."""
195
196 self.libraries = copy (libnames)
197
198
199 def add_library_dir (self, dir):
200 """Add 'dir' to the list of directories that will be searched for
201 libraries specified to 'add_library()' and 'set_libraries()'.
202 The linker will be instructed to search for libraries in the
203 order they are supplied to 'add_library_dir()' and/or
204 'set_library_dirs()'."""
205 self.library_dirs.append (dir)
206
207 def set_library_dirs (self, dirs):
208 """Set the list of library search directories to 'dirs' (a list
209 of strings). This does not affect any standard library
210 search path that the linker may search by default."""
211 self.library_dirs = copy (dirs)
212
213
Greg Warde1aaaa61999-08-14 23:50:50 +0000214 def add_runtime_library_dir (self, dir):
215 """Add 'dir' to the list of directories that will be searched for
216 shared libraries at runtime."""
217 self.runtime_library_dirs.append (dir)
218
219 def set_runtime_library_dirs (self, dirs):
220 """Set the list of directories to search for shared libraries
221 at runtime to 'dirs' (a list of strings). This does not affect
222 any standard search path that the runtime linker may search by
223 default."""
224 self.runtime_library_dirs = copy (dirs)
225
226
Greg Ward3f81cf71999-07-10 02:03:53 +0000227 def add_link_object (self, object):
228 """Add 'object' to the list of object files (or analogues, such
229 as explictly named library files or the output of "resource
230 compilers") to be included in every link driven by this
231 compiler object."""
232 self.objects.append (object)
233
234 def set_link_objects (self, objects):
235 """Set the list of object files (or analogues) to be included
236 in every link to 'objects'. This does not affect any
237 standard object files that the linker may include by default
238 (such as system libraries)."""
239 self.objects = copy (objects)
240
241
242 # -- Worker methods ------------------------------------------------
243 # (must be implemented by subclasses)
244
245 def compile (self,
246 sources,
247 macros=None,
248 includes=None):
249 """Compile one or more C/C++ source files. 'sources' must be
250 a list of strings, each one the name of a C/C++ source
251 file. Return a list of the object filenames generated
252 (one for each source filename in 'sources').
253
254 'macros', if given, must be a list of macro definitions. A
255 macro definition is either a (name, value) 2-tuple or a (name,)
256 1-tuple. The former defines a macro; if the value is None, the
257 macro is defined without an explicit value. The 1-tuple case
258 undefines a macro. Later definitions/redefinitions/
259 undefinitions take precedence.
260
261 'includes', if given, must be a list of strings, the directories
262 to add to the default include file search path for this
263 compilation only."""
264 pass
265
266
267 # XXX this is kind of useless without 'link_binary()' or
268 # 'link_executable()' or something -- or maybe 'link_static_lib()'
269 # should not exist at all, and we just have 'link_binary()'?
270 def link_static_lib (self,
271 objects,
272 output_libname,
273 libraries=None,
274 library_dirs=None):
275 """Link a bunch of stuff together to create a static library
276 file. The "bunch of stuff" consists of the list of object
277 files supplied as 'objects', the extra object files supplied
278 to 'add_link_object()' and/or 'set_link_objects()', the
279 libraries supplied to 'add_library()' and/or
280 'set_libraries()', and the libraries supplied as 'libraries'
281 (if any).
282
283 'output_libname' should be a library name, not a filename;
284 the filename will be inferred from the library name.
285
286 'library_dirs', if supplied, should be a list of additional
287 directories to search on top of the system default and those
288 supplied to 'add_library_dir()' and/or 'set_library_dirs()'."""
289
290 pass
291
292
Greg Wardf7a39ec1999-09-08 02:29:08 +0000293 # XXX passing in 'build_info' here is a kludge to deal with the
294 # oddities of one particular compiler (Visual C++). For some reason,
295 # it needs to be told about ".def" files, and currently the
296 # 'build_info' hash allows this through a 'def_file' element. The link
297 # methods for VC++ look for 'def_file' and transform it into the
298 # appropriate command-line options. The current code is objectionable
299 # for a number of reasons: 1) if the link methods take 'build_info',
300 # why bother passing in libraries, library_dirs, etc.? 2) if the link
301 # methods do it, why not the compile methods? 3) build_info is part of
302 # the interface between setup.py and the 'build_ext' command -- it
303 # should stop there and not be propagated down into the compiler
304 # classes! and 4) I don't like elevating a platform- and
305 # compiler-specific oddity to "first-class" status in 'build_info' (oh
306 # well, at least it's not being reified in the compiler classes -- that
307 # would be really gross).
308 #
309 # Possible solutions:
310 # - just pass build_info to all the compile/link methods,
311 # never mind all those other parameters and screw the
312 # integrity of the interfaces
313 # - add a mechanism for passing platform-specific and/or
314 # compiler-specific compiler/linker options from setup.py
315 # straight through to the appropriate compiler class
316
Greg Ward3f81cf71999-07-10 02:03:53 +0000317 def link_shared_lib (self,
318 objects,
319 output_libname,
320 libraries=None,
Greg Ward26e48ea1999-08-29 18:17:36 +0000321 library_dirs=None,
322 build_info=None):
Greg Ward3f81cf71999-07-10 02:03:53 +0000323 """Link a bunch of stuff together to create a shared library
324 file. Has the same effect as 'link_static_lib()' except
325 that the filename inferred from 'output_libname' will most
326 likely be different, and the type of file generated will
327 almost certainly be different."""
328 pass
329
330 def link_shared_object (self,
331 objects,
332 output_filename,
333 libraries=None,
Greg Ward26e48ea1999-08-29 18:17:36 +0000334 library_dirs=None,
335 build_info=None):
Greg Ward3f81cf71999-07-10 02:03:53 +0000336 """Link a bunch of stuff together to create a shared object
337 file. Much like 'link_shared_lib()', except the output
338 filename is explicitly supplied as 'output_filename'."""
339 pass
340
Greg Warde1aaaa61999-08-14 23:50:50 +0000341
342 # -- Filename mangling methods -------------------------------------
343
Greg Ward26e48ea1999-08-29 18:17:36 +0000344 def object_filenames (self, source_filenames):
Greg Warde1aaaa61999-08-14 23:50:50 +0000345 """Return the list of object filenames corresponding to each
346 specified source filename."""
347 pass
348
Greg Ward26e48ea1999-08-29 18:17:36 +0000349 def shared_object_filename (self, source_filename):
Greg Warde1aaaa61999-08-14 23:50:50 +0000350 """Return the shared object filename corresponding to a
351 specified source filename."""
352 pass
353
Greg Ward26e48ea1999-08-29 18:17:36 +0000354 def library_filename (self, libname):
Greg Warde1aaaa61999-08-14 23:50:50 +0000355 """Return the static library filename corresponding to the
356 specified library name."""
357
358 pass
359
Greg Ward26e48ea1999-08-29 18:17:36 +0000360 def shared_library_filename (self, libname):
Greg Warde1aaaa61999-08-14 23:50:50 +0000361 """Return the shared library filename corresponding to the
362 specified library name."""
363 pass
364
Greg Ward26e48ea1999-08-29 18:17:36 +0000365
366 def object_name (self, inname):
367 """Given a name with no extension, return the name + object extension"""
368 return inname + self._obj_ext
369
370 def shared_library_name (self, inname):
371 """Given a name with no extension, return the name + shared object extension"""
372 return inname + self._shared_lib_ext
Greg Warde1aaaa61999-08-14 23:50:50 +0000373
374 # -- Utility methods -----------------------------------------------
375
376 def spawn (self, cmd):
377 spawn (cmd, verbose=self.verbose, dry_run=self.dry_run)
378
379
Greg Ward3f81cf71999-07-10 02:03:53 +0000380# class CCompiler
381
382
Greg Warde1aaaa61999-08-14 23:50:50 +0000383def new_compiler (plat=None,
384 verbose=0,
385 dry_run=0):
Greg Ward3f81cf71999-07-10 02:03:53 +0000386 """Generate a CCompiler instance for platform 'plat' (or the
387 current platform, if 'plat' not supplied). Really instantiates
388 some concrete subclass of CCompiler, of course."""
389
390 if plat is None: plat = os.name
391 if plat == 'posix':
392 from unixccompiler import UnixCCompiler
Greg Warde1aaaa61999-08-14 23:50:50 +0000393 return UnixCCompiler (verbose, dry_run)
Greg Wardf7a39ec1999-09-08 02:29:08 +0000394 elif plat == 'nt':
Greg Ward26e48ea1999-08-29 18:17:36 +0000395 from msvccompiler import MSVCCompiler
396 return MSVCCompiler ( verbose, dry_run )
Greg Ward3f81cf71999-07-10 02:03:53 +0000397 else:
398 raise DistutilsPlatformError, \
399 "don't know how to compile C/C++ code on platform %s" % plat
Greg Wardf7a39ec1999-09-08 02:29:08 +0000400
401
402def gen_preprocess_options (macros, includes):
403 """Generate C pre-processor options (-D, -U, -I) as used by at
404 least two types of compilers: the typical Unix compiler and Visual
405 C++. 'macros' is the usual thing, a list of 1- or 2-tuples, where
406 (name,) means undefine (-U) macro 'name', and (name,value) means
407 define (-D) macro 'name' to 'value'. 'includes' is just a list of
408 directory names to be added to the header file search path (-I).
409 Returns a list of command-line options suitable for either
410 Unix compilers or Visual C++."""
411
412 # XXX it would be nice (mainly aesthetic, and so we don't generate
413 # stupid-looking command lines) to go over 'macros' and eliminate
414 # redundant definitions/undefinitions (ie. ensure that only the
415 # latest mention of a particular macro winds up on the command
416 # line). I don't think it's essential, though, since most (all?)
417 # Unix C compilers only pay attention to the latest -D or -U
418 # mention of a macro on their command line. Similar situation for
419 # 'includes'. I'm punting on both for now. Anyways, weeding out
420 # redundancies like this should probably be the province of
421 # CCompiler, since the data structures used are inherited from it
422 # and therefore common to all CCompiler classes.
423
424 pp_opts = []
425 for macro in macros:
426 if len (macro) == 1: # undefine this macro
427 pp_opts.append ("-U%s" % macro[0])
428 elif len (macro) == 2:
429 if macro[1] is None: # define with no explicit value
430 pp_opts.append ("-D%s" % macro[0])
431 else:
432 # XXX *don't* need to be clever about quoting the
433 # macro value here, because we're going to avoid the
434 # shell at all costs when we spawn the command!
435 pp_opts.append ("-D%s=%s" % macro)
436
437 for dir in includes:
438 pp_opts.append ("-I%s" % dir)
439
440 return pp_opts
441
442# gen_preprocess_options ()
443
444
445def gen_lib_options (libraries, library_dirs, lib_format, dir_format):
446 """Generate linker options for searching library directories and
447 linking with specific libraries. 'libraries' and 'library_dirs'
448 are, respectively, lists of library names (not filenames!) and
449 search directories. 'lib_format' is a format string with exactly
450 one "%s", into which will be plugged each library name in turn;
451 'dir_format' is similar, but directory names will be plugged into
452 it. Returns a list of command-line options suitable for use with
453 some compiler (depending on the two format strings passed in)."""
454
455 lib_opts = []
456
457 for dir in library_dirs:
458 lib_opts.append (dir_format % dir)
459
460 # XXX it's important that we *not* remove redundant library mentions!
461 # sometimes you really do have to say "-lfoo -lbar -lfoo" in order to
462 # resolve all symbols. I just hope we never have to say "-lfoo obj.o
463 # -lbar" to get things to work -- that's certainly a possibility, but a
464 # pretty nasty way to arrange your C code.
465
466 for lib in libraries:
467 lib_opts.append (lib_format % lib)
468
469 return lib_opts
470
471# _gen_lib_options ()