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:
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!
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.
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.
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.
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
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.
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
)
123 context
.Display("%s\n" % msg
)
133 context
.Display("Checking if building a %s file works... " % lang
)
134 ret
= context
.BuildProg(text
, suffix
)
135 _YesNoResult(context
, ret
, None, text
)
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... ")
154 ret
= _check_empty_program(context
, 'CC', text
, 'C')
155 _YesNoResult(context
, ret
, None, text
)
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... ")
174 ret
= _check_empty_program(context
, 'SHCC', text
, 'C', use_shared
= True)
175 _YesNoResult(context
, ret
, None, text
)
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... ")
194 ret
= _check_empty_program(context
, 'CXX', text
, 'C++')
195 _YesNoResult(context
, ret
, None, text
)
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... ")
214 ret
= _check_empty_program(context
, 'SHCXX', text
, 'C++', use_shared
= True)
215 _YesNoResult(context
, ret
, None, text
)
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
224 lang
, suffix
, msg
= _lang2suffix(language
)
229 return context
.CompileSharedObject(text
, suffix
)
231 return context
.CompileProg(text
, suffix
)
234 def CheckFunc(context
, function_name
, header
= None, language
= None):
236 Configure check for a function "function_name".
237 "language" should be "C" or "C++" and is used to select the compiler.
239 Optional "header" can be defined to define a function prototype, include a
240 header file or anything else that comes before main().
241 Sets HAVE_function_name in context.havedict according to the result.
242 Note that this uses the current value of compiler and linker flags, make
243 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
244 Returns an empty string for success, an error message for failure.
247 # Remarks from autoconf:
248 # - Don't include <ctype.h> because on OSF/1 3.0 it includes <sys/types.h>
249 # which includes <sys/select.h> which contains a prototype for select.
250 # Similarly for bzero.
251 # - assert.h is included to define __stub macros and hopefully few
252 # prototypes, which can conflict with char $1(); below.
253 # - Override any gcc2 internal prototype to avoid an error.
254 # - We use char for the function declaration because int might match the
255 # return type of a gcc2 builtin and then its argument prototype would
257 # - The GNU C library defines this for functions which it implements to
258 # always fail with ENOSYS. Some functions are actually named something
259 # starting with __ and the normal name is an alias.
261 if context
.headerfilename
:
262 includetext
= '#include "%s"' % context
.headerfilename
270 char %s(void);""" % function_name
272 lang
, suffix
, msg
= _lang2suffix(language
)
274 context
.Display("Cannot check for %s(): %s\n" % (function_name
, msg
))
282 #if _MSC_VER && !__INTEL_COMPILER
283 #pragma function(%(name)s)
287 #if defined (__stub_%(name)s) || defined (__stub___%(name)s)
288 #error "%(name)s has a GNU stub, cannot check"
295 """ % { 'name': function_name
,
296 'include': includetext
,
299 context
.Display("Checking for %s function %s()... " % (lang
, function_name
))
300 ret
= context
.BuildProg(text
, suffix
)
301 _YesNoResult(context
, ret
, "HAVE_" + function_name
, text
,
302 "Define to 1 if the system has the function `%s'." %\
307 def CheckHeader(context
, header_name
, header
=None, language
=None,
308 include_quotes
=None):
310 Configure check for a C or C++ header file "header_name".
311 Optional "header" can be defined to do something before including the
312 header file (unusual, supported for consistency).
313 "language" should be "C" or "C++" and is used to select the compiler.
315 Sets HAVE_header_name in context.havedict according to the result.
316 Note that this uses the current value of compiler and linker flags, make
317 sure $CFLAGS and $CPPFLAGS are set correctly.
318 Returns an empty string for success, an error message for failure.
320 # Why compile the program instead of just running the preprocessor?
321 # It is possible that the header file exists, but actually using it may
322 # fail (e.g., because it depends on other header files). Thus this test is
323 # more strict. It may require using the "header" argument.
325 # Use <> by default, because the check is normally used for system header
326 # files. SCons passes '""' to overrule this.
328 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
329 if context
.headerfilename
:
330 includetext
= '#include "%s"\n' % context
.headerfilename
336 lang
, suffix
, msg
= _lang2suffix(language
)
338 context
.Display("Cannot check for header file %s: %s\n"
339 % (header_name
, msg
))
342 if not include_quotes
:
343 include_quotes
= "<>"
345 text
= "%s%s\n#include %s%s%s\n\n" % (includetext
, header
,
346 include_quotes
[0], header_name
, include_quotes
[1])
348 context
.Display("Checking for %s header file %s... " % (lang
, header_name
))
349 ret
= context
.CompileProg(text
, suffix
)
350 _YesNoResult(context
, ret
, "HAVE_" + header_name
, text
,
351 "Define to 1 if you have the <%s> header file." % header_name
)
355 def CheckType(context
, type_name
, fallback
= None,
356 header
= None, language
= None):
358 Configure check for a C or C++ type "type_name".
359 Optional "header" can be defined to include a header file.
360 "language" should be "C" or "C++" and is used to select the compiler.
362 Sets HAVE_type_name in context.havedict according to the result.
363 Note that this uses the current value of compiler and linker flags, make
364 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
365 Returns an empty string for success, an error message for failure.
368 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
369 if context
.headerfilename
:
370 includetext
= '#include "%s"' % context
.headerfilename
376 lang
, suffix
, msg
= _lang2suffix(language
)
378 context
.Display("Cannot check for %s type: %s\n" % (type_name
, msg
))
381 # Remarks from autoconf about this test:
382 # - Grepping for the type in include files is not reliable (grep isn't
384 # - Using "TYPE my_var;" doesn't work for const qualified types in C++.
385 # Adding an initializer is not valid for some C++ classes.
386 # - Using the type as parameter to a function either fails for K&$ C or for
388 # - Using "TYPE *my_var;" is valid in C for some types that are not
389 # declared (struct something).
390 # - Using "sizeof(TYPE)" is valid when TYPE is actually a variable.
391 # - Using the previous two together works reliably.
399 if (sizeof (%(name)s))
402 """ % { 'include': includetext
,
406 context
.Display("Checking for %s type %s... " % (lang
, type_name
))
407 ret
= context
.BuildProg(text
, suffix
)
408 _YesNoResult(context
, ret
, "HAVE_" + type_name
, text
,
409 "Define to 1 if the system has the type `%s'." % type_name
)
410 if ret
and fallback
and context
.headerfilename
:
411 f
= open(context
.headerfilename
, "a")
412 f
.write("typedef %s %s;\n" % (fallback
, type_name
))
417 def CheckTypeSize(context
, type_name
, header
= None, language
= None, expect
= None):
418 """This check can be used to get the size of a given type, or to check whether
419 the type is of expected size.
424 - includes : sequence
425 list of headers to include in the test code before testing the type
429 if given, will test wether the type has the given number of bytes.
430 If not given, will automatically find the size.
434 0 if the check failed, or the found size of the type if the check succeeded."""
436 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
437 if context
.headerfilename
:
438 includetext
= '#include "%s"' % context
.headerfilename
445 lang
, suffix
, msg
= _lang2suffix(language
)
447 context
.Display("Cannot check for %s type: %s\n" % (type_name
, msg
))
450 src
= includetext
+ header
451 if expect
is not None:
452 # Only check if the given size is the right one
453 context
.Display('Checking %s is %d bytes... ' % (type_name
, expect
))
455 # test code taken from autoconf: this is a pretty clever hack to find that
456 # a type is of a given size using only compilation. This speeds things up
457 # quite a bit compared to straightforward code using TryRun
459 typedef %s scons_check_type;
463 static int test_array[1 - 2 * !(((long int) (sizeof(scons_check_type))) == %d)];
470 st
= context
.CompileProg(src
% (type_name
, expect
), suffix
)
472 context
.Display("yes\n")
473 _Have(context
, "SIZEOF_%s" % type_name
, expect
,
474 "The size of `%s', as computed by sizeof." % type_name
)
477 context
.Display("no\n")
478 _LogFailed(context
, src
, st
)
481 # Only check if the given size is the right one
482 context
.Message('Checking size of %s ... ' % type_name
)
484 # We have to be careful with the program we wish to test here since
485 # compilation will be attempted using the current environment's flags.
486 # So make sure that the program will compile without any warning. For
487 # example using: 'int main(int argc, char** argv)' will fail with the
488 # '-Wall -Werror' flags since the variables argc and argv would not be
489 # used in the program...
495 printf("%d", (int)sizeof(""" + type_name
+ """));
499 st
, out
= context
.RunProg(src
, suffix
)
503 # If cannot convert output of test prog to an integer (the size),
504 # something went wront, so just fail
509 context
.Display("yes\n")
510 _Have(context
, "SIZEOF_%s" % type_name
, size
,
511 "The size of `%s', as computed by sizeof." % type_name
)
514 context
.Display("no\n")
515 _LogFailed(context
, src
, st
)
520 def CheckDeclaration(context
, symbol
, includes
= None, language
= None):
521 """Checks whether symbol is declared.
523 Use the same test as autoconf, that is test whether the symbol is defined
524 as a macro or can be used as an r-value.
530 Optional "header" can be defined to include a header file.
532 only C and C++ supported.
536 True if the check failed, False if succeeded."""
538 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
539 if context
.headerfilename
:
540 includetext
= '#include "%s"' % context
.headerfilename
547 lang
, suffix
, msg
= _lang2suffix(language
)
549 context
.Display("Cannot check for declaration %s: %s\n" % (symbol
, msg
))
552 src
= includetext
+ includes
553 context
.Display('Checking whether %s is declared... ' % symbol
)
564 """ % (symbol
, symbol
)
566 st
= context
.CompileProg(src
, suffix
)
567 _YesNoResult(context
, st
, "HAVE_DECL_" + symbol
, src
,
568 "Set to 1 if %s is defined." % symbol
)
572 def CheckMember(context
, aggregate_member
, header
= None, language
= None):
574 Configure check for a C or C++ member "aggregate_member".
575 Optional "header" can be defined to include a header file.
576 "language" should be "C" or "C++" and is used to select the compiler.
578 Note that this uses the current value of compiler and linker flags, make
579 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
582 aggregate_member : str
583 the member to check. For example, 'struct tm.tm_gmtoff'.
585 Optional "header" can be defined to include a header file.
587 only C and C++ supported.
589 Returns the status (0 or False = Passed, True/non-zero = Failed).
592 lang
, suffix
, msg
= _lang2suffix(language
)
594 context
.Display("Cannot check for member %s: %s\n" % (aggregate_member
, msg
))
596 context
.Display("Checking for %s member %s... " % (lang
, aggregate_member
))
597 fields
= aggregate_member
.split('.')
599 msg
= "shall contain just one dot, for example 'struct tm.tm_gmtoff'"
600 context
.Display("Cannot check for member %s: %s\n" % (aggregate_member
, msg
))
602 aggregate
, member
= fields
[0], fields
[1]
604 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
605 if context
.headerfilename
:
606 includetext
= '#include "%s"' % context
.headerfilename
616 if (sizeof ((%(aggregate)s *) 0)->%(member)s)
618 }''' % {'include': includetext
,
620 'aggregate': aggregate
,
623 ret
= context
.BuildProg(text
, suffix
)
624 _YesNoResult(context
, ret
, "HAVE_" + aggregate_member
, text
,
625 "Define to 1 if the system has the member `%s`." % aggregate_member
)
628 def CheckLib(context
, libs
, func_name
= None, header
= None,
629 extra_libs
= None, call
= None, language
= None, autoadd
: int = 1,
630 append
: bool=True, unique
: bool=False):
632 Configure check for a C or C++ libraries "libs". Searches through
633 the list of libraries, until one is found where the test succeeds.
634 Tests if "func_name" or "call" exists in the library. Note: if it exists
635 in another library the test succeeds anyway!
636 Optional "header" can be defined to include a header file. If not given a
637 default prototype for "func_name" is added.
638 Optional "extra_libs" is a list of library names to be added after
639 "lib_name" in the build command. To be used for libraries that "lib_name"
641 Optional "call" replaces the call to "func_name" in the test code. It must
642 consist of complete C statements, including a trailing ";".
643 Both "func_name" and "call" arguments are optional, and in that case, just
644 linking against the libs is tested.
645 "language" should be "C" or "C++" and is used to select the compiler.
647 Note that this uses the current value of compiler and linker flags, make
648 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
649 Returns an empty string for success, an error message for failure.
651 # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
652 if context
.headerfilename
:
653 includetext
= '#include "%s"' % context
.headerfilename
661 %s""" % (includetext
, header
)
663 # Add a function declaration if needed.
664 if func_name
and func_name
!= "main":
673 # The actual test code.
675 call
= "%s();" % func_name
677 # if no function to test, leave main() blank
689 calltext
= call
[:i
] + ".."
690 elif call
[-1] == ';':
695 for lib_name
in libs
:
697 lang
, suffix
, msg
= _lang2suffix(language
)
699 context
.Display("Cannot check for library %s: %s\n" % (lib_name
, msg
))
702 # if a function was specified to run in main(), say it
704 context
.Display("Checking for %s in %s library %s... "
705 % (calltext
, lang
, lib_name
))
706 # otherwise, just say the name of library and language
708 context
.Display("Checking for %s library %s... "
716 oldLIBS
= context
.AppendLIBS(l
, unique
)
718 oldLIBS
= context
.PrependLIBS(l
, unique
)
719 sym
= "HAVE_LIB" + lib_name
724 ret
= context
.BuildProg(text
, suffix
)
726 _YesNoResult(context
, ret
, sym
, text
,
727 "Define to 1 if you have the `%s' library." % lib_name
)
728 if oldLIBS
!= -1 and (ret
or not autoadd
):
729 context
.SetLIBS(oldLIBS
)
736 def CheckProg(context
, prog_name
):
738 Configure check for a specific program.
740 Check whether program prog_name exists in path. If it is found,
741 returns the path for it, otherwise returns None.
743 context
.Display("Checking whether %s program exists..." % prog_name
)
744 path
= context
.env
.WhereIs(prog_name
)
746 context
.Display(path
+ "\n")
748 context
.Display("no\n")
753 # END OF PUBLIC FUNCTIONS
756 def _YesNoResult(context
, ret
, key
, text
, comment
= None) -> None:
758 Handle the result of a test with a "yes" or "no" result.
761 - `ret` is the return value: empty if OK, error message when not.
762 - `key` is the name of the symbol to be defined (HAVE_foo).
763 - `text` is the source code of the program used for testing.
764 - `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.
767 _Have(context
, key
, not ret
, comment
)
769 context
.Display("no\n")
770 _LogFailed(context
, text
, ret
)
772 context
.Display("yes\n")
775 def _Have(context
, key
, have
, comment
= None) -> None:
777 Store result of a test in context.havedict and context.headerfilename.
780 - `key` - is a "HAVE_abc" name. It is turned into all CAPITALS and non-alphanumerics are replaced by an underscore.
781 - `have` - value as it should appear in the header file, include quotes when desired and escape special characters!
782 - `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.
785 The value of "have" can be:
786 - 1 - Feature is defined, add "#define key".
787 - 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.
788 - number - Feature is defined to this number "#define key have". Doesn't work for 0 or 1, use a string then.
789 - string - Feature is defined to this string "#define key have".
794 key_up
= re
.sub('[^A-Z0-9_]', '_', key_up
)
795 context
.havedict
[key_up
] = have
797 line
= "#define %s 1\n" % key_up
799 line
= "/* #undef %s */\n" % key_up
800 elif isinstance(have
, int):
801 line
= "#define %s %d\n" % (key_up
, have
)
803 line
= "#define %s %s\n" % (key_up
, str(have
))
805 if comment
is not None:
806 lines
= "\n/* %s */\n" % comment
+ line
810 if context
.headerfilename
:
811 f
= open(context
.headerfilename
, "a")
814 elif hasattr(context
,'config_h'):
815 context
.config_h
= context
.config_h
+ lines
818 def _LogFailed(context
, text
, msg
) -> None:
820 Write to the log about a failed program.
821 Add line numbers, so that error messages can be understood.
824 context
.Log("Failed program was:\n")
825 lines
= text
.split('\n')
826 if len(lines
) and lines
[-1] == '':
827 lines
= lines
[:-1] # remove trailing empty line
830 context
.Log("%d: %s\n" % (n
, line
))
833 context
.Log("Error message: %s\n" % msg
)
836 def _lang2suffix(lang
):
838 Convert a language name to a suffix.
839 When "lang" is empty or None C is assumed.
840 Returns a tuple (lang, suffix, None) when it works.
841 For an unrecognized language returns (None, None, msg).
844 - lang = the unified language name
845 - suffix = the suffix, including the leading dot
846 - msg = an error message
848 if not lang
or lang
in ["C", "c"]:
849 return ("C", ".c", None)
850 if lang
in ["c++", "C++", "cpp", "CXX", "cxx"]:
851 return ("C++", ".cpp", None)
853 return None, None, "Unsupported language: %s" % lang
856 # vim: set sw=4 et sts=4 tw=79 fo+=l:
860 # indent-tabs-mode:nil
862 # vim: set expandtab tabstop=4 shiftwidth=4: