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, funcargs
= 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 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
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
275 char %s(void);""" % function_name
277 lang
, suffix
, msg
= _lang2suffix(language
)
279 context
.Display("Cannot check for %s(): %s\n" % (function_name
, msg
))
290 #if _MSC_VER && !__INTEL_COMPILER
291 #pragma function(%(name)s)
295 #if defined (__stub_%(name)s) || defined (__stub___%(name)s)
296 #error "%(name)s has a GNU stub, cannot check"
303 """ % { 'name': function_name
,
304 'include': includetext
,
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'." %\
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.
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
345 lang
, suffix
, msg
= _lang2suffix(language
)
347 context
.Display("Cannot check for header file %s: %s\n"
348 % (header_name
, 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
)
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.
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
385 lang
, suffix
, msg
= _lang2suffix(language
)
387 context
.Display("Cannot check for %s type: %s\n" % (type_name
, msg
))
390 # Remarks from autoconf about this test:
391 # - Grepping for the type in include files is not reliable (grep isn't
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
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.
408 if (sizeof (%(name)s))
411 """ % { 'include': includetext
,
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
))
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.
433 - includes : sequence
434 list of headers to include in the test code before testing the type
438 if given, will test wether the type has the given number of bytes.
439 If not given, will automatically find the size.
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
454 lang
, suffix
, msg
= _lang2suffix(language
)
456 context
.Display("Cannot check for %s type: %s\n" % (type_name
, 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
468 typedef %s scons_check_type;
472 static int test_array[1 - 2 * !(((long int) (sizeof(scons_check_type))) == %d)];
479 st
= context
.CompileProg(src
% (type_name
, expect
), suffix
)
481 context
.Display("yes\n")
482 _Have(context
, "SIZEOF_%s" % type_name
, expect
,
483 "The size of `%s', as computed by sizeof." % type_name
)
486 context
.Display("no\n")
487 _LogFailed(context
, src
, st
)
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...
504 printf("%d", (int)sizeof(""" + type_name
+ """));
508 st
, out
= context
.RunProg(src
, suffix
)
512 # If cannot convert output of test prog to an integer (the size),
513 # something went wront, so just fail
518 context
.Display("yes\n")
519 _Have(context
, "SIZEOF_%s" % type_name
, size
,
520 "The size of `%s', as computed by sizeof." % type_name
)
523 context
.Display("no\n")
524 _LogFailed(context
, src
, st
)
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.
539 Optional "header" can be defined to include a header file.
541 only C and C++ supported.
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
556 lang
, suffix
, msg
= _lang2suffix(language
)
558 context
.Display("Cannot check for declaration %s: %s\n" % (symbol
, msg
))
561 src
= includetext
+ includes
562 context
.Display('Checking whether %s is declared... ' % symbol
)
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
)
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.
587 Note that this uses the current value of compiler and linker flags, make
588 sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
591 aggregate_member : str
592 the member to check. For example, 'struct tm.tm_gmtoff'.
594 Optional "header" can be defined to include a header file.
596 only C and C++ supported.
598 Returns the status (0 or False = Passed, True/non-zero = Failed).
601 lang
, suffix
, msg
= _lang2suffix(language
)
603 context
.Display("Cannot check for member %s: %s\n" % (aggregate_member
, msg
))
605 context
.Display("Checking for %s member %s... " % (lang
, aggregate_member
))
606 fields
= aggregate_member
.split('.')
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
))
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
625 if (sizeof ((%(aggregate)s *) 0)->%(member)s)
627 }''' % {'include': includetext
,
629 'aggregate': aggregate
,
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
)
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"
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.
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
670 %s""" % (includetext
, header
)
672 # Add a function declaration if needed.
673 if func_name
and func_name
!= "main":
682 # The actual test code.
684 call
= "%s();" % func_name
686 # if no function to test, leave main() blank
697 calltext
= call
[:i
] + ".."
698 elif call
[-1] == ';':
703 for lib_name
in libs
:
705 lang
, suffix
, msg
= _lang2suffix(language
)
707 context
.Display("Cannot check for library %s: %s\n" % (lib_name
, msg
))
710 # if a function was specified to run in main(), say it
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
716 context
.Display("Checking for %s library %s... "
724 oldLIBS
= context
.AppendLIBS(l
, unique
)
726 oldLIBS
= context
.PrependLIBS(l
, unique
)
727 sym
= "HAVE_LIB" + lib_name
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
)
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
)
754 context
.Display(path
+ "\n")
756 context
.Display("no\n")
761 # END OF PUBLIC FUNCTIONS
764 def _YesNoResult(context
, ret
, key
, text
, comment
= None) -> None:
766 Handle the result of a test with a "yes" or "no" result.
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.
775 _Have(context
, key
, not ret
, comment
)
777 context
.Display("no\n")
778 _LogFailed(context
, text
, ret
)
780 context
.Display("yes\n")
783 def _Have(context
, key
, have
, comment
= None) -> None:
785 Store result of a test in context.havedict and context.headerfilename.
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".
802 key_up
= re
.sub('[^A-Z0-9_]', '_', key_up
)
803 context
.havedict
[key_up
] = have
805 line
= "#define %s 1\n" % key_up
807 line
= "/* #undef %s */\n" % key_up
808 elif isinstance(have
, int):
809 line
= "#define %s %d\n" % (key_up
, have
)
811 line
= "#define %s %s\n" % (key_up
, str(have
))
813 if comment
is not None:
814 lines
= "\n/* %s */\n" % comment
+ line
818 if context
.headerfilename
:
819 f
= open(context
.headerfilename
, "a")
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.
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
838 context
.Log("%d: %s\n" % (n
, line
))
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).
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:
868 # indent-tabs-mode:nil
870 # vim: set expandtab tabstop=4 shiftwidth=4: