blob: 02e22d2b3e59df281d21490992bb9989d31993f9 [file] [log] [blame]
Tarek Ziade1231a4e2011-05-19 13:07:25 +02001"""Abstract base class for compilers.
2
3This modules contains CCompiler, an abstract base class that defines the
4interface for the compiler abstraction model used by packaging.
5"""
6
7import os
Tarek Ziade1231a4e2011-05-19 13:07:25 +02008from shutil import move
9from packaging import logger
10from packaging.util import split_quoted, execute, newer_group, spawn
11from packaging.errors import (CompileError, LinkError, UnknownFileError)
12from packaging.compiler import gen_preprocess_options
13
14
15class CCompiler:
16 """Abstract base class to define the interface that must be implemented
17 by real compiler classes. Also has some utility methods used by
18 several compiler classes.
19
20 The basic idea behind a compiler abstraction class is that each
21 instance can be used for all the compile/link steps in building a
22 single project. Thus, attributes common to all of those compile and
23 link steps -- include directories, macros to define, libraries to link
24 against, etc. -- are attributes of the compiler instance. To allow for
25 variability in how individual files are treated, most of those
26 attributes may be varied on a per-compilation or per-link basis.
27 """
28
29 # 'name' is a class attribute that identifies this class. It
30 # keeps code that wants to know what kind of compiler it's dealing with
31 # from having to import all possible compiler classes just to do an
32 # 'isinstance'.
33 name = None
34 description = None
35
36 # XXX things not handled by this compiler abstraction model:
37 # * client can't provide additional options for a compiler,
38 # e.g. warning, optimization, debugging flags. Perhaps this
39 # should be the domain of concrete compiler abstraction classes
40 # (UnixCCompiler, MSVCCompiler, etc.) -- or perhaps the base
41 # class should have methods for the common ones.
42 # * can't completely override the include or library searchg
43 # path, ie. no "cc -I -Idir1 -Idir2" or "cc -L -Ldir1 -Ldir2".
44 # I'm not sure how widely supported this is even by Unix
45 # compilers, much less on other platforms. And I'm even less
46 # sure how useful it is; maybe for cross-compiling, but
47 # support for that is a ways off. (And anyways, cross
48 # compilers probably have a dedicated binary with the
49 # right paths compiled in. I hope.)
50 # * can't do really freaky things with the library list/library
51 # dirs, e.g. "-Ldir1 -lfoo -Ldir2 -lfoo" to link against
52 # different versions of libfoo.a in different locations. I
53 # think this is useless without the ability to null out the
54 # library search path anyways.
55
56
57 # Subclasses that rely on the standard filename generation methods
58 # implemented below should override these; see the comment near
59 # those methods ('object_filenames()' et. al.) for details:
60 src_extensions = None # list of strings
61 obj_extension = None # string
62 static_lib_extension = None
63 shared_lib_extension = None # string
64 static_lib_format = None # format string
65 shared_lib_format = None # prob. same as static_lib_format
66 exe_extension = None # string
67
68 # Default language settings. language_map is used to detect a source
69 # file or Extension target language, checking source filenames.
70 # language_order is used to detect the language precedence, when deciding
71 # what language to use when mixing source types. For example, if some
72 # extension has two files with ".c" extension, and one with ".cpp", it
73 # is still linked as c++.
74 language_map = {".c": "c",
75 ".cc": "c++",
76 ".cpp": "c++",
77 ".cxx": "c++",
78 ".m": "objc",
79 }
80 language_order = ["c++", "objc", "c"]
81
82 def __init__(self, verbose=0, dry_run=False, force=False):
83 self.dry_run = dry_run
84 self.force = force
85 self.verbose = verbose
86
87 # 'output_dir': a common output directory for object, library,
88 # shared object, and shared library files
89 self.output_dir = None
90
91 # 'macros': a list of macro definitions (or undefinitions). A
92 # macro definition is a 2-tuple (name, value), where the value is
93 # either a string or None (no explicit value). A macro
94 # undefinition is a 1-tuple (name,).
95 self.macros = []
96
97 # 'include_dirs': a list of directories to search for include files
98 self.include_dirs = []
99
100 # 'libraries': a list of libraries to include in any link
101 # (library names, not filenames: eg. "foo" not "libfoo.a")
102 self.libraries = []
103
104 # 'library_dirs': a list of directories to search for libraries
105 self.library_dirs = []
106
107 # 'runtime_library_dirs': a list of directories to search for
108 # shared libraries/objects at runtime
109 self.runtime_library_dirs = []
110
111 # 'objects': a list of object files (or similar, such as explicitly
112 # named library files) to include on any link
113 self.objects = []
114
115 for key, value in self.executables.items():
116 self.set_executable(key, value)
117
118 def set_executables(self, **args):
119 """Define the executables (and options for them) that will be run
120 to perform the various stages of compilation. The exact set of
121 executables that may be specified here depends on the compiler
122 class (via the 'executables' class attribute), but most will have:
123 compiler the C/C++ compiler
124 linker_so linker used to create shared objects and libraries
125 linker_exe linker used to create binary executables
126 archiver static library creator
127
128 On platforms with a command line (Unix, DOS/Windows), each of these
129 is a string that will be split into executable name and (optional)
130 list of arguments. (Splitting the string is done similarly to how
131 Unix shells operate: words are delimited by spaces, but quotes and
132 backslashes can override this. See
133 'distutils.util.split_quoted()'.)
134 """
135
136 # Note that some CCompiler implementation classes will define class
137 # attributes 'cpp', 'cc', etc. with hard-coded executable names;
138 # this is appropriate when a compiler class is for exactly one
139 # compiler/OS combination (eg. MSVCCompiler). Other compiler
140 # classes (UnixCCompiler, in particular) are driven by information
141 # discovered at run-time, since there are many different ways to do
142 # basically the same things with Unix C compilers.
143
144 for key, value in args.items():
145 if key not in self.executables:
146 raise ValueError("unknown executable '%s' for class %s" % \
147 (key, self.__class__.__name__))
148 self.set_executable(key, value)
149
150 def set_executable(self, key, value):
151 if isinstance(value, str):
152 setattr(self, key, split_quoted(value))
153 else:
154 setattr(self, key, value)
155
156 def _find_macro(self, name):
157 i = 0
158 for defn in self.macros:
159 if defn[0] == name:
160 return i
161 i = i + 1
162 return None
163
164 def _check_macro_definitions(self, definitions):
165 """Ensures that every element of 'definitions' is a valid macro
166 definition, ie. either (name,value) 2-tuple or a (name,) tuple. Do
167 nothing if all definitions are OK, raise TypeError otherwise.
168 """
169 for defn in definitions:
170 if not (isinstance(defn, tuple) and
171 (len(defn) == 1 or
172 (len(defn) == 2 and
173 (isinstance(defn[1], str) or defn[1] is None))) and
174 isinstance(defn[0], str)):
175 raise TypeError(("invalid macro definition '%s': " % defn) + \
176 "must be tuple (string,), (string, string), or " + \
177 "(string, None)")
178
179
180 # -- Bookkeeping methods -------------------------------------------
181
182 def define_macro(self, name, value=None):
183 """Define a preprocessor macro for all compilations driven by this
184 compiler object. The optional parameter 'value' should be a
185 string; if it is not supplied, then the macro will be defined
186 without an explicit value and the exact outcome depends on the
187 compiler used (XXX true? does ANSI say anything about this?)
188 """
189 # Delete from the list of macro definitions/undefinitions if
190 # already there (so that this one will take precedence).
191 i = self._find_macro(name)
192 if i is not None:
193 del self.macros[i]
194
195 defn = (name, value)
196 self.macros.append(defn)
197
198 def undefine_macro(self, name):
199 """Undefine a preprocessor macro for all compilations driven by
200 this compiler object. If the same macro is defined by
201 'define_macro()' and undefined by 'undefine_macro()' the last call
202 takes precedence (including multiple redefinitions or
203 undefinitions). If the macro is redefined/undefined on a
204 per-compilation basis (ie. in the call to 'compile()'), then that
205 takes precedence.
206 """
207 # Delete from the list of macro definitions/undefinitions if
208 # already there (so that this one will take precedence).
209 i = self._find_macro(name)
210 if i is not None:
211 del self.macros[i]
212
213 undefn = (name,)
214 self.macros.append(undefn)
215
216 def add_include_dir(self, dir):
217 """Add 'dir' to the list of directories that will be searched for
218 header files. The compiler is instructed to search directories in
219 the order in which they are supplied by successive calls to
220 'add_include_dir()'.
221 """
222 self.include_dirs.append(dir)
223
224 def set_include_dirs(self, dirs):
225 """Set the list of directories that will be searched to 'dirs' (a
226 list of strings). Overrides any preceding calls to
227 'add_include_dir()'; subsequence calls to 'add_include_dir()' add
228 to the list passed to 'set_include_dirs()'. This does not affect
229 any list of standard include directories that the compiler may
230 search by default.
231 """
232 self.include_dirs = dirs[:]
233
234 def add_library(self, libname):
235 """Add 'libname' to the list of libraries that will be included in
236 all links driven by this compiler object. Note that 'libname'
237 should *not* be the name of a file containing a library, but the
238 name of the library itself: the actual filename will be inferred by
239 the linker, the compiler, or the compiler class (depending on the
240 platform).
241
242 The linker will be instructed to link against libraries in the
243 order they were supplied to 'add_library()' and/or
244 'set_libraries()'. It is perfectly valid to duplicate library
245 names; the linker will be instructed to link against libraries as
246 many times as they are mentioned.
247 """
248 self.libraries.append(libname)
249
250 def set_libraries(self, libnames):
251 """Set the list of libraries to be included in all links driven by
252 this compiler object to 'libnames' (a list of strings). This does
253 not affect any standard system libraries that the linker may
254 include by default.
255 """
256 self.libraries = libnames[:]
257
258
259 def add_library_dir(self, dir):
260 """Add 'dir' to the list of directories that will be searched for
261 libraries specified to 'add_library()' and 'set_libraries()'. The
262 linker will be instructed to search for libraries in the order they
263 are supplied to 'add_library_dir()' and/or 'set_library_dirs()'.
264 """
265 self.library_dirs.append(dir)
266
267 def set_library_dirs(self, dirs):
268 """Set the list of library search directories to 'dirs' (a list of
269 strings). This does not affect any standard library search path
270 that the linker may search by default.
271 """
272 self.library_dirs = dirs[:]
273
274 def add_runtime_library_dir(self, dir):
275 """Add 'dir' to the list of directories that will be searched for
276 shared libraries at runtime.
277 """
278 self.runtime_library_dirs.append(dir)
279
280 def set_runtime_library_dirs(self, dirs):
281 """Set the list of directories to search for shared libraries at
282 runtime to 'dirs' (a list of strings). This does not affect any
283 standard search path that the runtime linker may search by
284 default.
285 """
286 self.runtime_library_dirs = dirs[:]
287
288 def add_link_object(self, object):
289 """Add 'object' to the list of object files (or analogues, such as
290 explicitly named library files or the output of "resource
291 compilers") to be included in every link driven by this compiler
292 object.
293 """
294 self.objects.append(object)
295
296 def set_link_objects(self, objects):
297 """Set the list of object files (or analogues) to be included in
298 every link to 'objects'. This does not affect any standard object
299 files that the linker may include by default (such as system
300 libraries).
301 """
302 self.objects = objects[:]
303
304
305 # -- Private utility methods --------------------------------------
306 # (here for the convenience of subclasses)
307
308 # Helper method to prep compiler in subclass compile() methods
309 def _setup_compile(self, outdir, macros, incdirs, sources, depends,
310 extra):
311 """Process arguments and decide which source files to compile."""
312 if outdir is None:
313 outdir = self.output_dir
314 elif not isinstance(outdir, str):
315 raise TypeError("'output_dir' must be a string or None")
316
317 if macros is None:
318 macros = self.macros
319 elif isinstance(macros, list):
320 macros = macros + (self.macros or [])
321 else:
322 raise TypeError("'macros' (if supplied) must be a list of tuples")
323
324 if incdirs is None:
325 incdirs = self.include_dirs
326 elif isinstance(incdirs, (list, tuple)):
327 incdirs = list(incdirs) + (self.include_dirs or [])
328 else:
329 raise TypeError(
330 "'include_dirs' (if supplied) must be a list of strings")
331
332 if extra is None:
333 extra = []
334
335 # Get the list of expected output (object) files
336 objects = self.object_filenames(sources,
337 strip_dir=False,
338 output_dir=outdir)
339 assert len(objects) == len(sources)
340
341 pp_opts = gen_preprocess_options(macros, incdirs)
342
343 build = {}
344 for i in range(len(sources)):
345 src = sources[i]
346 obj = objects[i]
347 ext = os.path.splitext(src)[1]
348 self.mkpath(os.path.dirname(obj))
349 build[obj] = (src, ext)
350
351 return macros, objects, extra, pp_opts, build
352
353 def _get_cc_args(self, pp_opts, debug, before):
Éric Araujo25987d02011-06-01 15:20:44 +0200354 # works for unixccompiler and cygwinccompiler
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200355 cc_args = pp_opts + ['-c']
356 if debug:
357 cc_args[:0] = ['-g']
358 if before:
359 cc_args[:0] = before
360 return cc_args
361
362 def _fix_compile_args(self, output_dir, macros, include_dirs):
363 """Typecheck and fix-up some of the arguments to the 'compile()'
364 method, and return fixed-up values. Specifically: if 'output_dir'
365 is None, replaces it with 'self.output_dir'; ensures that 'macros'
366 is a list, and augments it with 'self.macros'; ensures that
367 'include_dirs' is a list, and augments it with 'self.include_dirs'.
368 Guarantees that the returned values are of the correct type,
369 i.e. for 'output_dir' either string or None, and for 'macros' and
370 'include_dirs' either list or None.
371 """
372 if output_dir is None:
373 output_dir = self.output_dir
374 elif not isinstance(output_dir, str):
375 raise TypeError("'output_dir' must be a string or None")
376
377 if macros is None:
378 macros = self.macros
379 elif isinstance(macros, list):
380 macros = macros + (self.macros or [])
381 else:
382 raise TypeError("'macros' (if supplied) must be a list of tuples")
383
384 if include_dirs is None:
385 include_dirs = self.include_dirs
386 elif isinstance(include_dirs, (list, tuple)):
387 include_dirs = list(include_dirs) + (self.include_dirs or [])
388 else:
389 raise TypeError(
390 "'include_dirs' (if supplied) must be a list of strings")
391
392 return output_dir, macros, include_dirs
393
394 def _fix_object_args(self, objects, output_dir):
395 """Typecheck and fix up some arguments supplied to various methods.
396 Specifically: ensure that 'objects' is a list; if output_dir is
397 None, replace with self.output_dir. Return fixed versions of
398 'objects' and 'output_dir'.
399 """
400 if not isinstance(objects, (list, tuple)):
401 raise TypeError("'objects' must be a list or tuple of strings")
402 objects = list(objects)
403
404 if output_dir is None:
405 output_dir = self.output_dir
406 elif not isinstance(output_dir, str):
407 raise TypeError("'output_dir' must be a string or None")
408
409 return objects, output_dir
410
411 def _fix_lib_args(self, libraries, library_dirs, runtime_library_dirs):
412 """Typecheck and fix up some of the arguments supplied to the
413 'link_*' methods. Specifically: ensure that all arguments are
414 lists, and augment them with their permanent versions
415 (eg. 'self.libraries' augments 'libraries'). Return a tuple with
416 fixed versions of all arguments.
417 """
418 if libraries is None:
419 libraries = self.libraries
420 elif isinstance(libraries, (list, tuple)):
421 libraries = list(libraries) + (self.libraries or [])
422 else:
423 raise TypeError(
424 "'libraries' (if supplied) must be a list of strings")
425
426 if library_dirs is None:
427 library_dirs = self.library_dirs
428 elif isinstance(library_dirs, (list, tuple)):
429 library_dirs = list(library_dirs) + (self.library_dirs or [])
430 else:
431 raise TypeError(
432 "'library_dirs' (if supplied) must be a list of strings")
433
434 if runtime_library_dirs is None:
435 runtime_library_dirs = self.runtime_library_dirs
436 elif isinstance(runtime_library_dirs, (list, tuple)):
437 runtime_library_dirs = (list(runtime_library_dirs) +
438 (self.runtime_library_dirs or []))
439 else:
440 raise TypeError("'runtime_library_dirs' (if supplied) "
441 "must be a list of strings")
442
443 return libraries, library_dirs, runtime_library_dirs
444
445 def _need_link(self, objects, output_file):
446 """Return true if we need to relink the files listed in 'objects'
447 to recreate 'output_file'.
448 """
449 if self.force:
450 return True
451 else:
452 if self.dry_run:
453 newer = newer_group(objects, output_file, missing='newer')
454 else:
455 newer = newer_group(objects, output_file)
456 return newer
457
458 def detect_language(self, sources):
459 """Detect the language of a given file, or list of files. Uses
460 language_map, and language_order to do the job.
461 """
462 if not isinstance(sources, list):
463 sources = [sources]
464 lang = None
465 index = len(self.language_order)
466 for source in sources:
467 base, ext = os.path.splitext(source)
468 extlang = self.language_map.get(ext)
469 try:
470 extindex = self.language_order.index(extlang)
471 if extindex < index:
472 lang = extlang
473 index = extindex
474 except ValueError:
475 pass
476 return lang
477
478 # -- Worker methods ------------------------------------------------
479 # (must be implemented by subclasses)
480
481 def preprocess(self, source, output_file=None, macros=None,
482 include_dirs=None, extra_preargs=None, extra_postargs=None):
483 """Preprocess a single C/C++ source file, named in 'source'.
484 Output will be written to file named 'output_file', or stdout if
485 'output_file' not supplied. 'macros' is a list of macro
486 definitions as for 'compile()', which will augment the macros set
487 with 'define_macro()' and 'undefine_macro()'. 'include_dirs' is a
488 list of directory names that will be added to the default list.
489
490 Raises PreprocessError on failure.
491 """
492 pass
493
494 def compile(self, sources, output_dir=None, macros=None,
495 include_dirs=None, debug=False, extra_preargs=None,
496 extra_postargs=None, depends=None):
497 """Compile one or more source files.
498
499 'sources' must be a list of filenames, most likely C/C++
500 files, but in reality anything that can be handled by a
501 particular compiler and compiler class (eg. MSVCCompiler can
502 handle resource files in 'sources'). Return a list of object
503 filenames, one per source filename in 'sources'. Depending on
504 the implementation, not all source files will necessarily be
505 compiled, but all corresponding object filenames will be
506 returned.
507
508 If 'output_dir' is given, object files will be put under it, while
509 retaining their original path component. That is, "foo/bar.c"
510 normally compiles to "foo/bar.o" (for a Unix implementation); if
511 'output_dir' is "build", then it would compile to
512 "build/foo/bar.o".
513
514 'macros', if given, must be a list of macro definitions. A macro
515 definition is either a (name, value) 2-tuple or a (name,) 1-tuple.
516 The former defines a macro; if the value is None, the macro is
517 defined without an explicit value. The 1-tuple case undefines a
518 macro. Later definitions/redefinitions/ undefinitions take
519 precedence.
520
521 'include_dirs', if given, must be a list of strings, the
522 directories to add to the default include file search path for this
523 compilation only.
524
525 'debug' is a boolean; if true, the compiler will be instructed to
526 output debug symbols in (or alongside) the object file(s).
527
528 'extra_preargs' and 'extra_postargs' are implementation- dependent.
529 On platforms that have the notion of a command line (e.g. Unix,
530 DOS/Windows), they are most likely lists of strings: extra
531 command-line arguments to prepand/append to the compiler command
532 line. On other platforms, consult the implementation class
533 documentation. In any event, they are intended as an escape hatch
534 for those occasions when the abstract compiler framework doesn't
535 cut the mustard.
536
537 'depends', if given, is a list of filenames that all targets
538 depend on. If a source file is older than any file in
539 depends, then the source file will be recompiled. This
540 supports dependency tracking, but only at a coarse
541 granularity.
542
543 Raises CompileError on failure.
544 """
545 # A concrete compiler class can either override this method
546 # entirely or implement _compile().
547
548 macros, objects, extra_postargs, pp_opts, build = \
549 self._setup_compile(output_dir, macros, include_dirs, sources,
550 depends, extra_postargs)
551 cc_args = self._get_cc_args(pp_opts, debug, extra_preargs)
552
553 for obj in objects:
554 try:
555 src, ext = build[obj]
556 except KeyError:
557 continue
558 self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
559
560 # Return *all* object filenames, not just the ones we just built.
561 return objects
562
563 def _compile(self, obj, src, ext, cc_args, extra_postargs, pp_opts):
564 """Compile 'src' to product 'obj'."""
565
566 # A concrete compiler class that does not override compile()
567 # should implement _compile().
568 pass
569
570 def create_static_lib(self, objects, output_libname, output_dir=None,
571 debug=False, target_lang=None):
572 """Link a bunch of stuff together to create a static library file.
573 The "bunch of stuff" consists of the list of object files supplied
574 as 'objects', the extra object files supplied to
575 'add_link_object()' and/or 'set_link_objects()', the libraries
576 supplied to 'add_library()' and/or 'set_libraries()', and the
577 libraries supplied as 'libraries' (if any).
578
579 'output_libname' should be a library name, not a filename; the
580 filename will be inferred from the library name. 'output_dir' is
581 the directory where the library file will be put.
582
583 'debug' is a boolean; if true, debugging information will be
584 included in the library (note that on most platforms, it is the
585 compile step where this matters: the 'debug' flag is included here
586 just for consistency).
587
588 'target_lang' is the target language for which the given objects
589 are being compiled. This allows specific linkage time treatment of
590 certain languages.
591
592 Raises LibError on failure.
593 """
594 pass
595
596 # values for target_desc parameter in link()
597 SHARED_OBJECT = "shared_object"
598 SHARED_LIBRARY = "shared_library"
599 EXECUTABLE = "executable"
600
601 def link(self, target_desc, objects, output_filename, output_dir=None,
602 libraries=None, library_dirs=None, runtime_library_dirs=None,
603 export_symbols=None, debug=False, extra_preargs=None,
604 extra_postargs=None, build_temp=None, target_lang=None):
605 """Link a bunch of stuff together to create an executable or
606 shared library file.
607
608 The "bunch of stuff" consists of the list of object files supplied
609 as 'objects'. 'output_filename' should be a filename. If
610 'output_dir' is supplied, 'output_filename' is relative to it
611 (i.e. 'output_filename' can provide directory components if
612 needed).
613
614 'libraries' is a list of libraries to link against. These are
615 library names, not filenames, since they're translated into
616 filenames in a platform-specific way (eg. "foo" becomes "libfoo.a"
617 on Unix and "foo.lib" on DOS/Windows). However, they can include a
618 directory component, which means the linker will look in that
619 specific directory rather than searching all the normal locations.
620
621 'library_dirs', if supplied, should be a list of directories to
622 search for libraries that were specified as bare library names
623 (ie. no directory component). These are on top of the system
624 default and those supplied to 'add_library_dir()' and/or
625 'set_library_dirs()'. 'runtime_library_dirs' is a list of
626 directories that will be embedded into the shared library and used
627 to search for other shared libraries that *it* depends on at
628 run-time. (This may only be relevant on Unix.)
629
630 'export_symbols' is a list of symbols that the shared library will
631 export. (This appears to be relevant only on Windows.)
632
633 'debug' is as for 'compile()' and 'create_static_lib()', with the
634 slight distinction that it actually matters on most platforms (as
635 opposed to 'create_static_lib()', which includes a 'debug' flag
636 mostly for form's sake).
637
638 'extra_preargs' and 'extra_postargs' are as for 'compile()' (except
639 of course that they supply command-line arguments for the
640 particular linker being used).
641
642 'target_lang' is the target language for which the given objects
643 are being compiled. This allows specific linkage time treatment of
644 certain languages.
645
646 Raises LinkError on failure.
647 """
648 raise NotImplementedError
649
650
651 # Old 'link_*()' methods, rewritten to use the new 'link()' method.
652
653 def link_shared_lib(self, objects, output_libname, output_dir=None,
654 libraries=None, library_dirs=None,
655 runtime_library_dirs=None, export_symbols=None,
656 debug=False, extra_preargs=None, extra_postargs=None,
657 build_temp=None, target_lang=None):
658 self.link(CCompiler.SHARED_LIBRARY, objects,
659 self.library_filename(output_libname, lib_type='shared'),
660 output_dir,
661 libraries, library_dirs, runtime_library_dirs,
662 export_symbols, debug,
663 extra_preargs, extra_postargs, build_temp, target_lang)
664
665 def link_shared_object(self, objects, output_filename, output_dir=None,
666 libraries=None, library_dirs=None,
667 runtime_library_dirs=None, export_symbols=None,
668 debug=False, extra_preargs=None, extra_postargs=None,
669 build_temp=None, target_lang=None):
670 self.link(CCompiler.SHARED_OBJECT, objects,
671 output_filename, output_dir,
672 libraries, library_dirs, runtime_library_dirs,
673 export_symbols, debug,
674 extra_preargs, extra_postargs, build_temp, target_lang)
675
676 def link_executable(self, objects, output_progname, output_dir=None,
677 libraries=None, library_dirs=None,
678 runtime_library_dirs=None, debug=False,
679 extra_preargs=None, extra_postargs=None,
680 target_lang=None):
681 self.link(CCompiler.EXECUTABLE, objects,
682 self.executable_filename(output_progname), output_dir,
683 libraries, library_dirs, runtime_library_dirs, None,
684 debug, extra_preargs, extra_postargs, None, target_lang)
685
686
687 # -- Miscellaneous methods -----------------------------------------
688 # These are all used by the 'gen_lib_options() function; there is
689 # no appropriate default implementation so subclasses should
690 # implement all of these.
691
692 def library_dir_option(self, dir):
693 """Return the compiler option to add 'dir' to the list of
694 directories searched for libraries.
695 """
696 raise NotImplementedError
697
698 def runtime_library_dir_option(self, dir):
699 """Return the compiler option to add 'dir' to the list of
700 directories searched for runtime libraries.
701 """
702 raise NotImplementedError
703
704 def library_option(self, lib):
705 """Return the compiler option to add 'dir' to the list of libraries
706 linked into the shared library or executable.
707 """
708 raise NotImplementedError
709
710 def has_function(self, funcname, includes=None, include_dirs=None,
711 libraries=None, library_dirs=None):
712 """Return a boolean indicating whether funcname is supported on
713 the current platform. The optional arguments can be used to
714 augment the compilation environment.
715 """
716
717 # this can't be included at module scope because it tries to
718 # import math which might not be available at that point - maybe
719 # the necessary logic should just be inlined?
720 import tempfile
721 if includes is None:
722 includes = []
723 if include_dirs is None:
724 include_dirs = []
725 if libraries is None:
726 libraries = []
727 if library_dirs is None:
728 library_dirs = []
729 fd, fname = tempfile.mkstemp(".c", funcname, text=True)
Victor Stinner21a9c742011-05-19 15:51:27 +0200730 with os.fdopen(fd, "w") as f:
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200731 for incl in includes:
732 f.write("""#include "%s"\n""" % incl)
733 f.write("""\
734main (int argc, char **argv) {
735 %s();
736}
737""" % funcname)
Tarek Ziade1231a4e2011-05-19 13:07:25 +0200738 try:
739 objects = self.compile([fname], include_dirs=include_dirs)
740 except CompileError:
741 return False
742
743 try:
744 self.link_executable(objects, "a.out",
745 libraries=libraries,
746 library_dirs=library_dirs)
747 except (LinkError, TypeError):
748 return False
749 return True
750
751 def find_library_file(self, dirs, lib, debug=False):
752 """Search the specified list of directories for a static or shared
753 library file 'lib' and return the full path to that file. If
754 'debug' is true, look for a debugging version (if that makes sense on
755 the current platform). Return None if 'lib' wasn't found in any of
756 the specified directories.
757 """
758 raise NotImplementedError
759
760 # -- Filename generation methods -----------------------------------
761
762 # The default implementation of the filename generating methods are
763 # prejudiced towards the Unix/DOS/Windows view of the world:
764 # * object files are named by replacing the source file extension
765 # (eg. .c/.cpp -> .o/.obj)
766 # * library files (shared or static) are named by plugging the
767 # library name and extension into a format string, eg.
768 # "lib%s.%s" % (lib_name, ".a") for Unix static libraries
769 # * executables are named by appending an extension (possibly
770 # empty) to the program name: eg. progname + ".exe" for
771 # Windows
772 #
773 # To reduce redundant code, these methods expect to find
774 # several attributes in the current object (presumably defined
775 # as class attributes):
776 # * src_extensions -
777 # list of C/C++ source file extensions, eg. ['.c', '.cpp']
778 # * obj_extension -
779 # object file extension, eg. '.o' or '.obj'
780 # * static_lib_extension -
781 # extension for static library files, eg. '.a' or '.lib'
782 # * shared_lib_extension -
783 # extension for shared library/object files, eg. '.so', '.dll'
784 # * static_lib_format -
785 # format string for generating static library filenames,
786 # eg. 'lib%s.%s' or '%s.%s'
787 # * shared_lib_format
788 # format string for generating shared library filenames
789 # (probably same as static_lib_format, since the extension
790 # is one of the intended parameters to the format string)
791 # * exe_extension -
792 # extension for executable files, eg. '' or '.exe'
793
794 def object_filenames(self, source_filenames, strip_dir=False, output_dir=''):
795 if output_dir is None:
796 output_dir = ''
797 obj_names = []
798 for src_name in source_filenames:
799 base, ext = os.path.splitext(src_name)
800 base = os.path.splitdrive(base)[1] # Chop off the drive
801 base = base[os.path.isabs(base):] # If abs, chop off leading /
802 if ext not in self.src_extensions:
803 raise UnknownFileError("unknown file type '%s' (from '%s')" %
804 (ext, src_name))
805 if strip_dir:
806 base = os.path.basename(base)
807 obj_names.append(os.path.join(output_dir,
808 base + self.obj_extension))
809 return obj_names
810
811 def shared_object_filename(self, basename, strip_dir=False, output_dir=''):
812 assert output_dir is not None
813 if strip_dir:
814 basename = os.path.basename(basename)
815 return os.path.join(output_dir, basename + self.shared_lib_extension)
816
817 def executable_filename(self, basename, strip_dir=False, output_dir=''):
818 assert output_dir is not None
819 if strip_dir:
820 basename = os.path.basename(basename)
821 return os.path.join(output_dir, basename + (self.exe_extension or ''))
822
823 def library_filename(self, libname, lib_type='static', # or 'shared'
824 strip_dir=False, output_dir=''):
825 assert output_dir is not None
826 if lib_type not in ("static", "shared", "dylib"):
827 raise ValueError(
828 "'lib_type' must be 'static', 'shared' or 'dylib'")
829 fmt = getattr(self, lib_type + "_lib_format")
830 ext = getattr(self, lib_type + "_lib_extension")
831
832 dir, base = os.path.split(libname)
833 filename = fmt % (base, ext)
834 if strip_dir:
835 dir = ''
836
837 return os.path.join(output_dir, dir, filename)
838
839
840 # -- Utility methods -----------------------------------------------
841
842 def execute(self, func, args, msg=None, level=1):
843 execute(func, args, msg, self.dry_run)
844
845 def spawn(self, cmd):
846 spawn(cmd, dry_run=self.dry_run)
847
848 def move_file(self, src, dst):
849 logger.info("moving %r to %r", src, dst)
850 if self.dry_run:
851 return
852 return move(src, dst)
853
854 def mkpath(self, name, mode=0o777):
855 name = os.path.normpath(name)
856 if os.path.isdir(name) or name == '':
857 return
858 if self.dry_run:
859 head = ''
860 for part in name.split(os.sep):
861 logger.info("created directory %s%s", head, part)
862 head += part + os.sep
863 return
864 os.makedirs(name, mode)