Address mwichmann's feedback. Annotate with changed version and remove now obsolete...
[scons.git] / SCons / Conftest.py
blob79ede996892b5633318b8c6197683fb6cee64291
1 # MIT License
3 # Copyright The SCons Foundation
4 # Copyright (c) 2003 Stichting NLnet Labs
5 # Copyright (c) 2001, 2002, 2003 Steven Knight
7 # Permission is hereby granted, free of charge, to any person obtaining
8 # a copy of this software and associated documentation files (the
9 # "Software"), to deal in the Software without restriction, including
10 # without limitation the rights to use, copy, modify, merge, publish,
11 # distribute, sublicense, and/or sell copies of the Software, and to
12 # permit persons to whom the Software is furnished to do so, subject to
13 # the following conditions:
15 # The above copyright notice and this permission notice shall be included
16 # in all copies or substantial portions of the Software.
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
19 # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
20 # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
21 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
22 # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23 # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
24 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 r"""Autoconf-like configuration support
28 The purpose of this module is to define how a check is to be performed.
30 A context class is used that defines functions for carrying out the tests,
31 logging and messages. The following methods and members must be present:
33 context.Display(msg)
34 Function called to print messages that are normally displayed
35 for the user. Newlines are explicitly used. The text should
36 also be written to the logfile!
38 context.Log(msg)
39 Function called to write to a log file.
41 context.BuildProg(text, ext)
42 Function called to build a program, using "ext" for the file
43 extension. Must return an empty string for success, an error
44 message for failure. For reliable test results building should
45 be done just like an actual program would be build, using the
46 same command and arguments (including configure results so far).
48 context.CompileProg(text, ext)
49 Function called to compile a program, using "ext" for the file
50 extension. Must return an empty string for success, an error
51 message for failure. For reliable test results compiling should be
52 done just like an actual source file would be compiled, using the
53 same command and arguments (including configure results so far).
55 context.AppendLIBS(lib_name_list)
56 Append "lib_name_list" to the value of LIBS. "lib_namelist" is
57 a list of strings. Return the value of LIBS before changing it
58 (any type can be used, it is passed to SetLIBS() later.)
60 context.PrependLIBS(lib_name_list)
61 Prepend "lib_name_list" to the value of LIBS. "lib_namelist" is
62 a list of strings. Return the value of LIBS before changing it
63 (any type can be used, it is passed to SetLIBS() later.)
65 context.SetLIBS(value)
66 Set LIBS to "value". The type of "value" is what AppendLIBS()
67 returned. Return the value of LIBS before changing it (any type
68 can be used, it is passed to SetLIBS() later.)
70 context.headerfilename
71 Name of file to append configure results to, usually "confdefs.h".
72 The file must not exist or be empty when starting. Empty or None
73 to skip this (some tests will not work!).
75 context.config_h (may be missing).
76 If present, must be a string, which will be filled with the
77 contents of a config_h file.
79 context.vardict
80 Dictionary holding variables used for the tests and stores results
81 from the tests, used for the build commands. Normally contains
82 "CC", "LIBS", "CPPFLAGS", etc.
84 context.havedict
85 Dictionary holding results from the tests that are to be used
86 inside a program. Names often start with "HAVE\_". These are zero
87 (feature not present) or one (feature present). Other variables
88 may have any value, e.g., "PERLVERSION" can be a number and
89 "SYSTEMNAME" a string.
90 """
92 import re
95 # PUBLIC VARIABLES
98 LogInputFiles = 1 # Set that to log the input files in case of a failed test
99 LogErrorMessages = 1 # Set that to log Conftest-generated error messages
102 # PUBLIC FUNCTIONS
105 # Generic remarks:
106 # - When a language is specified which is not supported the test fails. The
107 # message is a bit different, because not all the arguments for the normal
108 # message are available yet (chicken-egg problem).
111 def CheckBuilder(context, text = None, language = None):
113 Configure check to see if the compiler works.
114 Note that this uses the current value of compiler and linker flags, make
115 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
116 "language" should be "C" or "C++" and is used to select the compiler.
117 Default is "C".
118 "text" may be used to specify the code to be build.
119 Returns an empty string for success, an error message for failure.
121 lang, suffix, msg = _lang2suffix(language)
122 if msg:
123 context.Display("%s\n" % msg)
124 return msg
126 if not text:
127 text = """
128 int main(void) {
129 return 0;
133 context.Display("Checking if building a %s file works... " % lang)
134 ret = context.BuildProg(text, suffix)
135 _YesNoResult(context, ret, None, text)
136 return ret
138 def CheckCC(context):
140 Configure check for a working C compiler.
142 This checks whether the C compiler, as defined in the $CC construction
143 variable, can compile a C source file. It uses the current $CCCOM value
144 too, so that it can test against non working flags.
147 context.Display("Checking whether the C compiler works... ")
148 text = """
149 int main(void)
151 return 0;
154 ret = _check_empty_program(context, 'CC', text, 'C')
155 _YesNoResult(context, ret, None, text)
156 return ret
158 def CheckSHCC(context):
160 Configure check for a working shared C compiler.
162 This checks whether the C compiler, as defined in the $SHCC construction
163 variable, can compile a C source file. It uses the current $SHCCCOM value
164 too, so that it can test against non working flags.
167 context.Display("Checking whether the (shared) C compiler works... ")
168 text = """
169 int foo(void)
171 return 0;
174 ret = _check_empty_program(context, 'SHCC', text, 'C', use_shared = True)
175 _YesNoResult(context, ret, None, text)
176 return ret
178 def CheckCXX(context):
180 Configure check for a working CXX compiler.
182 This checks whether the CXX compiler, as defined in the $CXX construction
183 variable, can compile a CXX source file. It uses the current $CXXCOM value
184 too, so that it can test against non working flags.
187 context.Display("Checking whether the C++ compiler works... ")
188 text = """
189 int main(void)
191 return 0;
194 ret = _check_empty_program(context, 'CXX', text, 'C++')
195 _YesNoResult(context, ret, None, text)
196 return ret
198 def CheckSHCXX(context):
200 Configure check for a working shared CXX compiler.
202 This checks whether the CXX compiler, as defined in the $SHCXX construction
203 variable, can compile a CXX source file. It uses the current $SHCXXCOM value
204 too, so that it can test against non working flags.
207 context.Display("Checking whether the (shared) C++ compiler works... ")
208 text = """
209 int main(void)
211 return 0;
214 ret = _check_empty_program(context, 'SHCXX', text, 'C++', use_shared = True)
215 _YesNoResult(context, ret, None, text)
216 return ret
218 def _check_empty_program(context, comp, text, language, use_shared: bool = False):
219 """Return 0 on success, 1 otherwise."""
220 if comp not in context.env or not context.env[comp]:
221 # The compiler construction variable is not set or empty
222 return 1
224 lang, suffix, msg = _lang2suffix(language)
225 if msg:
226 return 1
228 if use_shared:
229 return context.CompileSharedObject(text, suffix)
230 else:
231 return context.CompileProg(text, suffix)
234 def CheckFunc(context, function_name, header = None, language = None, funcargs = None):
236 Configure check for a function "function_name".
237 "language" should be "C" or "C++" and is used to select the compiler.
238 Default is "C".
239 Optional "header" can be defined to define a function prototype, include a
240 header file or anything else that comes before main().
241 Optional "funcargs" can be defined to define an argument list for the
242 generated function invocation.
243 Sets HAVE_function_name in context.havedict according to the result.
244 Note that this uses the current value of compiler and linker flags, make
245 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
246 Returns an empty string for success, an error message for failure.
248 .. versionchanged:: 4.7.0
249 The ``funcargs`` parameter was added.
252 # Remarks from autoconf:
253 # - Don't include <ctype.h> because on OSF/1 3.0 it includes <sys/types.h>
254 # which includes <sys/select.h> which contains a prototype for select.
255 # Similarly for bzero.
256 # - assert.h is included to define __stub macros and hopefully few
257 # prototypes, which can conflict with char $1(); below.
258 # - Override any gcc2 internal prototype to avoid an error.
259 # - We use char for the function declaration because int might match the
260 # return type of a gcc2 builtin and then its argument prototype would
261 # still apply.
262 # - The GNU C library defines this for functions which it implements to
263 # always fail with ENOSYS. Some functions are actually named something
264 # starting with __ and the normal name is an alias.
266 if context.headerfilename:
267 includetext = '#include "%s"' % context.headerfilename
268 else:
269 includetext = ''
270 if not header:
271 header = """
272 #ifdef __cplusplus
273 extern "C"
274 #endif
275 char %s(void);""" % function_name
277 lang, suffix, msg = _lang2suffix(language)
278 if msg:
279 context.Display("Cannot check for %s(): %s\n" % (function_name, msg))
280 return msg
282 if not funcargs:
283 funcargs = ''
285 text = """
286 %(include)s
287 #include <assert.h>
288 %(hdr)s
290 #if _MSC_VER && !__INTEL_COMPILER
291 #pragma function(%(name)s)
292 #endif
294 int main(void) {
295 #if defined (__stub_%(name)s) || defined (__stub___%(name)s)
296 #error "%(name)s has a GNU stub, cannot check"
297 #else
298 %(name)s(%(args)s);
299 #endif
301 return 0;
303 """ % { 'name': function_name,
304 'include': includetext,
305 'hdr': header,
306 'args': funcargs}
308 context.Display("Checking for %s function %s()... " % (lang, function_name))
309 ret = context.BuildProg(text, suffix)
310 _YesNoResult(context, ret, "HAVE_" + function_name, text,
311 "Define to 1 if the system has the function `%s'." %\
312 function_name)
313 return ret
316 def CheckHeader(context, header_name, header=None, language=None,
317 include_quotes=None):
319 Configure check for a C or C++ header file "header_name".
320 Optional "header" can be defined to do something before including the
321 header file (unusual, supported for consistency).
322 "language" should be "C" or "C++" and is used to select the compiler.
323 Default is "C".
324 Sets HAVE_header_name in context.havedict according to the result.
325 Note that this uses the current value of compiler and linker flags, make
326 sure $CFLAGS and $CPPFLAGS are set correctly.
327 Returns an empty string for success, an error message for failure.
329 # Why compile the program instead of just running the preprocessor?
330 # It is possible that the header file exists, but actually using it may
331 # fail (e.g., because it depends on other header files). Thus this test is
332 # more strict. It may require using the "header" argument.
334 # Use <> by default, because the check is normally used for system header
335 # files. SCons passes '""' to overrule this.
337 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
338 if context.headerfilename:
339 includetext = '#include "%s"\n' % context.headerfilename
340 else:
341 includetext = ''
342 if not header:
343 header = ""
345 lang, suffix, msg = _lang2suffix(language)
346 if msg:
347 context.Display("Cannot check for header file %s: %s\n"
348 % (header_name, msg))
349 return msg
351 if not include_quotes:
352 include_quotes = "<>"
354 text = "%s%s\n#include %s%s%s\n\n" % (includetext, header,
355 include_quotes[0], header_name, include_quotes[1])
357 context.Display("Checking for %s header file %s... " % (lang, header_name))
358 ret = context.CompileProg(text, suffix)
359 _YesNoResult(context, ret, "HAVE_" + header_name, text,
360 "Define to 1 if you have the <%s> header file." % header_name)
361 return ret
364 def CheckType(context, type_name, fallback = None,
365 header = None, language = None):
367 Configure check for a C or C++ type "type_name".
368 Optional "header" can be defined to include a header file.
369 "language" should be "C" or "C++" and is used to select the compiler.
370 Default is "C".
371 Sets HAVE_type_name in context.havedict according to the result.
372 Note that this uses the current value of compiler and linker flags, make
373 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
374 Returns an empty string for success, an error message for failure.
377 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
378 if context.headerfilename:
379 includetext = '#include "%s"' % context.headerfilename
380 else:
381 includetext = ''
382 if not header:
383 header = ""
385 lang, suffix, msg = _lang2suffix(language)
386 if msg:
387 context.Display("Cannot check for %s type: %s\n" % (type_name, msg))
388 return msg
390 # Remarks from autoconf about this test:
391 # - Grepping for the type in include files is not reliable (grep isn't
392 # portable anyway).
393 # - Using "TYPE my_var;" doesn't work for const qualified types in C++.
394 # Adding an initializer is not valid for some C++ classes.
395 # - Using the type as parameter to a function either fails for K&$ C or for
396 # C++.
397 # - Using "TYPE *my_var;" is valid in C for some types that are not
398 # declared (struct something).
399 # - Using "sizeof(TYPE)" is valid when TYPE is actually a variable.
400 # - Using the previous two together works reliably.
401 text = """
402 %(include)s
403 %(header)s
405 int main(void) {
406 if ((%(name)s *) 0)
407 return 0;
408 if (sizeof (%(name)s))
409 return 0;
411 """ % { 'include': includetext,
412 'header': header,
413 'name': type_name }
415 context.Display("Checking for %s type %s... " % (lang, type_name))
416 ret = context.BuildProg(text, suffix)
417 _YesNoResult(context, ret, "HAVE_" + type_name, text,
418 "Define to 1 if the system has the type `%s'." % type_name)
419 if ret and fallback and context.headerfilename:
420 f = open(context.headerfilename, "a")
421 f.write("typedef %s %s;\n" % (fallback, type_name))
422 f.close()
424 return ret
426 def CheckTypeSize(context, type_name, header = None, language = None, expect = None):
427 """This check can be used to get the size of a given type, or to check whether
428 the type is of expected size.
430 Arguments:
431 - type : str
432 the type to check
433 - includes : sequence
434 list of headers to include in the test code before testing the type
435 - language : str
436 'C' or 'C++'
437 - expect : int
438 if given, will test wether the type has the given number of bytes.
439 If not given, will automatically find the size.
441 Returns:
442 status : int
443 0 if the check failed, or the found size of the type if the check succeeded."""
445 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
446 if context.headerfilename:
447 includetext = '#include "%s"' % context.headerfilename
448 else:
449 includetext = ''
451 if not header:
452 header = ""
454 lang, suffix, msg = _lang2suffix(language)
455 if msg:
456 context.Display("Cannot check for %s type: %s\n" % (type_name, msg))
457 return msg
459 src = includetext + header
460 if expect is not None:
461 # Only check if the given size is the right one
462 context.Display('Checking %s is %d bytes... ' % (type_name, expect))
464 # test code taken from autoconf: this is a pretty clever hack to find that
465 # a type is of a given size using only compilation. This speeds things up
466 # quite a bit compared to straightforward code using TryRun
467 src = src + r"""
468 typedef %s scons_check_type;
470 int main(void)
472 static int test_array[1 - 2 * !(((long int) (sizeof(scons_check_type))) == %d)];
473 test_array[0] = 0;
475 return 0;
479 st = context.CompileProg(src % (type_name, expect), suffix)
480 if not st:
481 context.Display("yes\n")
482 _Have(context, "SIZEOF_%s" % type_name, expect,
483 "The size of `%s', as computed by sizeof." % type_name)
484 return expect
485 else:
486 context.Display("no\n")
487 _LogFailed(context, src, st)
488 return 0
489 else:
490 # Only check if the given size is the right one
491 context.Message('Checking size of %s ... ' % type_name)
493 # We have to be careful with the program we wish to test here since
494 # compilation will be attempted using the current environment's flags.
495 # So make sure that the program will compile without any warning. For
496 # example using: 'int main(int argc, char** argv)' will fail with the
497 # '-Wall -Werror' flags since the variables argc and argv would not be
498 # used in the program...
500 src = src + """
501 #include <stdlib.h>
502 #include <stdio.h>
503 int main(void) {
504 printf("%d", (int)sizeof(""" + type_name + """));
505 return 0;
508 st, out = context.RunProg(src, suffix)
509 try:
510 size = int(out)
511 except ValueError:
512 # If cannot convert output of test prog to an integer (the size),
513 # something went wront, so just fail
514 st = 1
515 size = 0
517 if not st:
518 context.Display("yes\n")
519 _Have(context, "SIZEOF_%s" % type_name, size,
520 "The size of `%s', as computed by sizeof." % type_name)
521 return size
522 else:
523 context.Display("no\n")
524 _LogFailed(context, src, st)
525 return 0
527 return 0
529 def CheckDeclaration(context, symbol, includes = None, language = None):
530 """Checks whether symbol is declared.
532 Use the same test as autoconf, that is test whether the symbol is defined
533 as a macro or can be used as an r-value.
535 Arguments:
536 symbol : str
537 the symbol to check
538 includes : str
539 Optional "header" can be defined to include a header file.
540 language : str
541 only C and C++ supported.
543 Returns:
544 status : bool
545 True if the check failed, False if succeeded."""
547 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
548 if context.headerfilename:
549 includetext = '#include "%s"' % context.headerfilename
550 else:
551 includetext = ''
553 if not includes:
554 includes = ""
556 lang, suffix, msg = _lang2suffix(language)
557 if msg:
558 context.Display("Cannot check for declaration %s: %s\n" % (symbol, msg))
559 return msg
561 src = includetext + includes
562 context.Display('Checking whether %s is declared... ' % symbol)
564 src = src + r"""
565 int main(void)
567 #ifndef %s
568 (void) %s;
569 #endif
571 return 0;
573 """ % (symbol, symbol)
575 st = context.CompileProg(src, suffix)
576 _YesNoResult(context, st, "HAVE_DECL_" + symbol, src,
577 "Set to 1 if %s is defined." % symbol)
578 return st
581 def CheckMember(context, aggregate_member, header = None, language = None):
583 Configure check for a C or C++ member "aggregate_member".
584 Optional "header" can be defined to include a header file.
585 "language" should be "C" or "C++" and is used to select the compiler.
586 Default is "C".
587 Note that this uses the current value of compiler and linker flags, make
588 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
590 Arguments:
591 aggregate_member : str
592 the member to check. For example, 'struct tm.tm_gmtoff'.
593 includes : str
594 Optional "header" can be defined to include a header file.
595 language : str
596 only C and C++ supported.
598 Returns the status (0 or False = Passed, True/non-zero = Failed).
601 lang, suffix, msg = _lang2suffix(language)
602 if msg:
603 context.Display("Cannot check for member %s: %s\n" % (aggregate_member, msg))
604 return True
605 context.Display("Checking for %s member %s... " % (lang, aggregate_member))
606 fields = aggregate_member.split('.')
607 if len(fields) != 2:
608 msg = "shall contain just one dot, for example 'struct tm.tm_gmtoff'"
609 context.Display("Cannot check for member %s: %s\n" % (aggregate_member, msg))
610 return True
611 aggregate, member = fields[0], fields[1]
613 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
614 if context.headerfilename:
615 includetext = '#include "%s"' % context.headerfilename
616 else:
617 includetext = ''
618 if not header:
619 header = ''
620 text = '''
621 %(include)s
622 %(header)s
624 int main(void) {
625 if (sizeof ((%(aggregate)s *) 0)->%(member)s)
626 return 0;
627 }''' % {'include': includetext,
628 'header': header,
629 'aggregate': aggregate,
630 'member': member}
632 ret = context.BuildProg(text, suffix)
633 _YesNoResult(context, ret, "HAVE_" + aggregate_member, text,
634 "Define to 1 if the system has the member `%s`." % aggregate_member)
635 return ret
637 def CheckLib(context, libs, func_name = None, header = None,
638 extra_libs = None, call = None, language = None, autoadd: int = 1,
639 append: bool=True, unique: bool=False):
641 Configure check for a C or C++ libraries "libs". Searches through
642 the list of libraries, until one is found where the test succeeds.
643 Tests if "func_name" or "call" exists in the library. Note: if it exists
644 in another library the test succeeds anyway!
645 Optional "header" can be defined to include a header file. If not given a
646 default prototype for "func_name" is added.
647 Optional "extra_libs" is a list of library names to be added after
648 "lib_name" in the build command. To be used for libraries that "lib_name"
649 depends on.
650 Optional "call" replaces the call to "func_name" in the test code. It must
651 consist of complete C statements, including a trailing ";".
652 Both "func_name" and "call" arguments are optional, and in that case, just
653 linking against the libs is tested.
654 "language" should be "C" or "C++" and is used to select the compiler.
655 Default is "C".
656 Note that this uses the current value of compiler and linker flags, make
657 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
658 Returns an empty string for success, an error message for failure.
660 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
661 if context.headerfilename:
662 includetext = '#include "%s"' % context.headerfilename
663 else:
664 includetext = ''
665 if not header:
666 header = ""
668 text = """
670 %s""" % (includetext, header)
672 # Add a function declaration if needed.
673 if func_name and func_name != "main":
674 if not header:
675 text = text + """
676 #ifdef __cplusplus
677 extern "C"
678 #endif
679 char %s();
680 """ % func_name
682 # The actual test code.
683 if not call:
684 call = "%s();" % func_name
686 # if no function to test, leave main() blank
687 text = text + """
688 int main(void) {
690 return 0;
692 """ % (call or "")
694 if call:
695 i = call.find("\n")
696 if i > 0:
697 calltext = call[:i] + ".."
698 elif call[-1] == ';':
699 calltext = call[:-1]
700 else:
701 calltext = call
703 for lib_name in libs:
705 lang, suffix, msg = _lang2suffix(language)
706 if msg:
707 context.Display("Cannot check for library %s: %s\n" % (lib_name, msg))
708 return msg
710 # if a function was specified to run in main(), say it
711 if call:
712 context.Display("Checking for %s in %s library %s... "
713 % (calltext, lang, lib_name))
714 # otherwise, just say the name of library and language
715 else:
716 context.Display("Checking for %s library %s... "
717 % (lang, lib_name))
719 if lib_name:
720 l = [ lib_name ]
721 if extra_libs:
722 l.extend(extra_libs)
723 if append:
724 oldLIBS = context.AppendLIBS(l, unique)
725 else:
726 oldLIBS = context.PrependLIBS(l, unique)
727 sym = "HAVE_LIB" + lib_name
728 else:
729 oldLIBS = -1
730 sym = None
732 ret = context.BuildProg(text, suffix)
734 _YesNoResult(context, ret, sym, text,
735 "Define to 1 if you have the `%s' library." % lib_name)
736 if oldLIBS != -1 and (ret or not autoadd):
737 context.SetLIBS(oldLIBS)
739 if not ret:
740 return ret
742 return ret
744 def CheckProg(context, prog_name):
746 Configure check for a specific program.
748 Check whether program prog_name exists in path. If it is found,
749 returns the path for it, otherwise returns None.
751 context.Display("Checking whether %s program exists..." % prog_name)
752 path = context.env.WhereIs(prog_name)
753 if path:
754 context.Display(path + "\n")
755 else:
756 context.Display("no\n")
757 return path
761 # END OF PUBLIC FUNCTIONS
764 def _YesNoResult(context, ret, key, text, comment = None) -> None:
765 r"""
766 Handle the result of a test with a "yes" or "no" result.
768 :Parameters:
769 - `ret` is the return value: empty if OK, error message when not.
770 - `key` is the name of the symbol to be defined (HAVE_foo).
771 - `text` is the source code of the program used for testing.
772 - `comment` is the C comment to add above the line defining the symbol (the comment is automatically put inside a /\* \*/). If None, no comment is added.
774 if key:
775 _Have(context, key, not ret, comment)
776 if ret:
777 context.Display("no\n")
778 _LogFailed(context, text, ret)
779 else:
780 context.Display("yes\n")
783 def _Have(context, key, have, comment = None) -> None:
784 r"""
785 Store result of a test in context.havedict and context.headerfilename.
787 :Parameters:
788 - `key` - is a "HAVE_abc" name. It is turned into all CAPITALS and non-alphanumerics are replaced by an underscore.
789 - `have` - value as it should appear in the header file, include quotes when desired and escape special characters!
790 - `comment` is the C comment to add above the line defining the symbol (the comment is automatically put inside a /\* \*/). If None, no comment is added.
793 The value of "have" can be:
794 - 1 - Feature is defined, add "#define key".
795 - 0 - Feature is not defined, add "/\* #undef key \*/". Adding "undef" is what autoconf does. Not useful for the compiler, but it shows that the test was done.
796 - number - Feature is defined to this number "#define key have". Doesn't work for 0 or 1, use a string then.
797 - string - Feature is defined to this string "#define key have".
801 key_up = key.upper()
802 key_up = re.sub('[^A-Z0-9_]', '_', key_up)
803 context.havedict[key_up] = have
804 if have == 1:
805 line = "#define %s 1\n" % key_up
806 elif have == 0:
807 line = "/* #undef %s */\n" % key_up
808 elif isinstance(have, int):
809 line = "#define %s %d\n" % (key_up, have)
810 else:
811 line = "#define %s %s\n" % (key_up, str(have))
813 if comment is not None:
814 lines = "\n/* %s */\n" % comment + line
815 else:
816 lines = "\n" + line
818 if context.headerfilename:
819 f = open(context.headerfilename, "a")
820 f.write(lines)
821 f.close()
822 elif hasattr(context,'config_h'):
823 context.config_h = context.config_h + lines
826 def _LogFailed(context, text, msg) -> None:
828 Write to the log about a failed program.
829 Add line numbers, so that error messages can be understood.
831 if LogInputFiles:
832 context.Log("Failed program was:\n")
833 lines = text.split('\n')
834 if len(lines) and lines[-1] == '':
835 lines = lines[:-1] # remove trailing empty line
836 n = 1
837 for line in lines:
838 context.Log("%d: %s\n" % (n, line))
839 n = n + 1
840 if LogErrorMessages:
841 context.Log("Error message: %s\n" % msg)
844 def _lang2suffix(lang):
846 Convert a language name to a suffix.
847 When "lang" is empty or None C is assumed.
848 Returns a tuple (lang, suffix, None) when it works.
849 For an unrecognized language returns (None, None, msg).
851 Where:
852 - lang = the unified language name
853 - suffix = the suffix, including the leading dot
854 - msg = an error message
856 if not lang or lang in ["C", "c"]:
857 return ("C", ".c", None)
858 if lang in ["c++", "C++", "cpp", "CXX", "cxx"]:
859 return ("C++", ".cpp", None)
861 return None, None, "Unsupported language: %s" % lang
864 # vim: set sw=4 et sts=4 tw=79 fo+=l:
866 # Local Variables:
867 # tab-width:4
868 # indent-tabs-mode:nil
869 # End:
870 # vim: set expandtab tabstop=4 shiftwidth=4: