You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

812 lines
28 KiB

6 years ago
  1. """SCons.Conftest
  2. Autoconf-like configuration support; low level implementation of tests.
  3. """
  4. #
  5. # Copyright (c) 2003 Stichting NLnet Labs
  6. # Copyright (c) 2001, 2002, 2003 Steven Knight
  7. #
  8. # Permission is hereby granted, free of charge, to any person obtaining
  9. # a copy of this software and associated documentation files (the
  10. # "Software"), to deal in the Software without restriction, including
  11. # without limitation the rights to use, copy, modify, merge, publish,
  12. # distribute, sublicense, and/or sell copies of the Software, and to
  13. # permit persons to whom the Software is furnished to do so, subject to
  14. # the following conditions:
  15. #
  16. # The above copyright notice and this permission notice shall be included
  17. # in all copies or substantial portions of the Software.
  18. #
  19. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
  20. # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
  21. # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  23. # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  24. # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  25. # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. #
  27. #
  28. # The purpose of this module is to define how a check is to be performed.
  29. # Use one of the Check...() functions below.
  30. #
  31. #
  32. # A context class is used that defines functions for carrying out the tests,
  33. # logging and messages. The following methods and members must be present:
  34. #
  35. # context.Display(msg) Function called to print messages that are normally
  36. # displayed for the user. Newlines are explicitly used.
  37. # The text should also be written to the logfile!
  38. #
  39. # context.Log(msg) Function called to write to a log file.
  40. #
  41. # context.BuildProg(text, ext)
  42. # Function called to build a program, using "ext" for the
  43. # file extention. Must return an empty string for
  44. # success, an error message for failure.
  45. # For reliable test results building should be done just
  46. # like an actual program would be build, using the same
  47. # command and arguments (including configure results so
  48. # far).
  49. #
  50. # context.CompileProg(text, ext)
  51. # Function called to compile a program, using "ext" for
  52. # the file extention. Must return an empty string for
  53. # success, an error message for failure.
  54. # For reliable test results compiling should be done just
  55. # like an actual source file would be compiled, using the
  56. # same command and arguments (including configure results
  57. # so far).
  58. #
  59. # context.AppendLIBS(lib_name_list)
  60. # Append "lib_name_list" to the value of LIBS.
  61. # "lib_namelist" is a list of strings.
  62. # Return the value of LIBS before changing it (any type
  63. # can be used, it is passed to SetLIBS() later.)
  64. #
  65. # context.PrependLIBS(lib_name_list)
  66. # Prepend "lib_name_list" to the value of LIBS.
  67. # "lib_namelist" is a list of strings.
  68. # Return the value of LIBS before changing it (any type
  69. # can be used, it is passed to SetLIBS() later.)
  70. #
  71. # context.SetLIBS(value)
  72. # Set LIBS to "value". The type of "value" is what
  73. # AppendLIBS() returned.
  74. # Return the value of LIBS before changing it (any type
  75. # can be used, it is passed to SetLIBS() later.)
  76. #
  77. # context.headerfilename
  78. # Name of file to append configure results to, usually
  79. # "confdefs.h".
  80. # The file must not exist or be empty when starting.
  81. # Empty or None to skip this (some tests will not work!).
  82. #
  83. # context.config_h (may be missing). If present, must be a string, which
  84. # will be filled with the contents of a config_h file.
  85. #
  86. # context.vardict Dictionary holding variables used for the tests and
  87. # stores results from the tests, used for the build
  88. # commands.
  89. # Normally contains "CC", "LIBS", "CPPFLAGS", etc.
  90. #
  91. # context.havedict Dictionary holding results from the tests that are to
  92. # be used inside a program.
  93. # Names often start with "HAVE_". These are zero
  94. # (feature not present) or one (feature present). Other
  95. # variables may have any value, e.g., "PERLVERSION" can
  96. # be a number and "SYSTEMNAME" a string.
  97. #
  98. import re
  99. #
  100. # PUBLIC VARIABLES
  101. #
  102. LogInputFiles = 1 # Set that to log the input files in case of a failed test
  103. LogErrorMessages = 1 # Set that to log Conftest-generated error messages
  104. #
  105. # PUBLIC FUNCTIONS
  106. #
  107. # Generic remarks:
  108. # - When a language is specified which is not supported the test fails. The
  109. # message is a bit different, because not all the arguments for the normal
  110. # message are available yet (chicken-egg problem).
  111. def CheckBuilder(context, text = None, language = None):
  112. """
  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.
  120. """
  121. lang, suffix, msg = _lang2suffix(language)
  122. if msg:
  123. context.Display("%s\n" % msg)
  124. return msg
  125. if not text:
  126. text = """
  127. int main() {
  128. return 0;
  129. }
  130. """
  131. context.Display("Checking if building a %s file works... " % lang)
  132. ret = context.BuildProg(text, suffix)
  133. _YesNoResult(context, ret, None, text)
  134. return ret
  135. def CheckCC(context):
  136. """
  137. Configure check for a working C compiler.
  138. This checks whether the C compiler, as defined in the $CC construction
  139. variable, can compile a C source file. It uses the current $CCCOM value
  140. too, so that it can test against non working flags.
  141. """
  142. context.Display("Checking whether the C compiler works... ")
  143. text = """
  144. int main()
  145. {
  146. return 0;
  147. }
  148. """
  149. ret = _check_empty_program(context, 'CC', text, 'C')
  150. _YesNoResult(context, ret, None, text)
  151. return ret
  152. def CheckSHCC(context):
  153. """
  154. Configure check for a working shared C compiler.
  155. This checks whether the C compiler, as defined in the $SHCC construction
  156. variable, can compile a C source file. It uses the current $SHCCCOM value
  157. too, so that it can test against non working flags.
  158. """
  159. context.Display("Checking whether the (shared) C compiler works... ")
  160. text = """
  161. int foo()
  162. {
  163. return 0;
  164. }
  165. """
  166. ret = _check_empty_program(context, 'SHCC', text, 'C', use_shared = True)
  167. _YesNoResult(context, ret, None, text)
  168. return ret
  169. def CheckCXX(context):
  170. """
  171. Configure check for a working CXX compiler.
  172. This checks whether the CXX compiler, as defined in the $CXX construction
  173. variable, can compile a CXX source file. It uses the current $CXXCOM value
  174. too, so that it can test against non working flags.
  175. """
  176. context.Display("Checking whether the C++ compiler works... ")
  177. text = """
  178. int main()
  179. {
  180. return 0;
  181. }
  182. """
  183. ret = _check_empty_program(context, 'CXX', text, 'C++')
  184. _YesNoResult(context, ret, None, text)
  185. return ret
  186. def CheckSHCXX(context):
  187. """
  188. Configure check for a working shared CXX compiler.
  189. This checks whether the CXX compiler, as defined in the $SHCXX construction
  190. variable, can compile a CXX source file. It uses the current $SHCXXCOM value
  191. too, so that it can test against non working flags.
  192. """
  193. context.Display("Checking whether the (shared) C++ compiler works... ")
  194. text = """
  195. int main()
  196. {
  197. return 0;
  198. }
  199. """
  200. ret = _check_empty_program(context, 'SHCXX', text, 'C++', use_shared = True)
  201. _YesNoResult(context, ret, None, text)
  202. return ret
  203. def _check_empty_program(context, comp, text, language, use_shared = False):
  204. """Return 0 on success, 1 otherwise."""
  205. if comp not in context.env or not context.env[comp]:
  206. # The compiler construction variable is not set or empty
  207. return 1
  208. lang, suffix, msg = _lang2suffix(language)
  209. if msg:
  210. return 1
  211. if use_shared:
  212. return context.CompileSharedObject(text, suffix)
  213. else:
  214. return context.CompileProg(text, suffix)
  215. def CheckFunc(context, function_name, header = None, language = None):
  216. """
  217. Configure check for a function "function_name".
  218. "language" should be "C" or "C++" and is used to select the compiler.
  219. Default is "C".
  220. Optional "header" can be defined to define a function prototype, include a
  221. header file or anything else that comes before main().
  222. Sets HAVE_function_name in context.havedict according to the result.
  223. Note that this uses the current value of compiler and linker flags, make
  224. sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
  225. Returns an empty string for success, an error message for failure.
  226. """
  227. # Remarks from autoconf:
  228. # - Don't include <ctype.h> because on OSF/1 3.0 it includes <sys/types.h>
  229. # which includes <sys/select.h> which contains a prototype for select.
  230. # Similarly for bzero.
  231. # - assert.h is included to define __stub macros and hopefully few
  232. # prototypes, which can conflict with char $1(); below.
  233. # - Override any gcc2 internal prototype to avoid an error.
  234. # - We use char for the function declaration because int might match the
  235. # return type of a gcc2 builtin and then its argument prototype would
  236. # still apply.
  237. # - The GNU C library defines this for functions which it implements to
  238. # always fail with ENOSYS. Some functions are actually named something
  239. # starting with __ and the normal name is an alias.
  240. if context.headerfilename:
  241. includetext = '#include "%s"' % context.headerfilename
  242. else:
  243. includetext = ''
  244. if not header:
  245. header = """
  246. #ifdef __cplusplus
  247. extern "C"
  248. #endif
  249. char %s();""" % function_name
  250. lang, suffix, msg = _lang2suffix(language)
  251. if msg:
  252. context.Display("Cannot check for %s(): %s\n" % (function_name, msg))
  253. return msg
  254. text = """
  255. %(include)s
  256. #include <assert.h>
  257. %(hdr)s
  258. int main() {
  259. #if defined (__stub_%(name)s) || defined (__stub___%(name)s)
  260. fail fail fail
  261. #else
  262. %(name)s();
  263. #endif
  264. return 0;
  265. }
  266. """ % { 'name': function_name,
  267. 'include': includetext,
  268. 'hdr': header }
  269. context.Display("Checking for %s function %s()... " % (lang, function_name))
  270. ret = context.BuildProg(text, suffix)
  271. _YesNoResult(context, ret, "HAVE_" + function_name, text,
  272. "Define to 1 if the system has the function `%s'." %\
  273. function_name)
  274. return ret
  275. def CheckHeader(context, header_name, header = None, language = None,
  276. include_quotes = None):
  277. """
  278. Configure check for a C or C++ header file "header_name".
  279. Optional "header" can be defined to do something before including the
  280. header file (unusual, supported for consistency).
  281. "language" should be "C" or "C++" and is used to select the compiler.
  282. Default is "C".
  283. Sets HAVE_header_name in context.havedict according to the result.
  284. Note that this uses the current value of compiler and linker flags, make
  285. sure $CFLAGS and $CPPFLAGS are set correctly.
  286. Returns an empty string for success, an error message for failure.
  287. """
  288. # Why compile the program instead of just running the preprocessor?
  289. # It is possible that the header file exists, but actually using it may
  290. # fail (e.g., because it depends on other header files). Thus this test is
  291. # more strict. It may require using the "header" argument.
  292. #
  293. # Use <> by default, because the check is normally used for system header
  294. # files. SCons passes '""' to overrule this.
  295. # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
  296. if context.headerfilename:
  297. includetext = '#include "%s"\n' % context.headerfilename
  298. else:
  299. includetext = ''
  300. if not header:
  301. header = ""
  302. lang, suffix, msg = _lang2suffix(language)
  303. if msg:
  304. context.Display("Cannot check for header file %s: %s\n"
  305. % (header_name, msg))
  306. return msg
  307. if not include_quotes:
  308. include_quotes = "<>"
  309. text = "%s%s\n#include %s%s%s\n\n" % (includetext, header,
  310. include_quotes[0], header_name, include_quotes[1])
  311. context.Display("Checking for %s header file %s... " % (lang, header_name))
  312. ret = context.CompileProg(text, suffix)
  313. _YesNoResult(context, ret, "HAVE_" + header_name, text,
  314. "Define to 1 if you have the <%s> header file." % header_name)
  315. return ret
  316. def CheckType(context, type_name, fallback = None,
  317. header = None, language = None):
  318. """
  319. Configure check for a C or C++ type "type_name".
  320. Optional "header" can be defined to include a header file.
  321. "language" should be "C" or "C++" and is used to select the compiler.
  322. Default is "C".
  323. Sets HAVE_type_name in context.havedict according to the result.
  324. Note that this uses the current value of compiler and linker flags, make
  325. sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
  326. Returns an empty string for success, an error message for failure.
  327. """
  328. # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
  329. if context.headerfilename:
  330. includetext = '#include "%s"' % context.headerfilename
  331. else:
  332. includetext = ''
  333. if not header:
  334. header = ""
  335. lang, suffix, msg = _lang2suffix(language)
  336. if msg:
  337. context.Display("Cannot check for %s type: %s\n" % (type_name, msg))
  338. return msg
  339. # Remarks from autoconf about this test:
  340. # - Grepping for the type in include files is not reliable (grep isn't
  341. # portable anyway).
  342. # - Using "TYPE my_var;" doesn't work for const qualified types in C++.
  343. # Adding an initializer is not valid for some C++ classes.
  344. # - Using the type as parameter to a function either fails for K&$ C or for
  345. # C++.
  346. # - Using "TYPE *my_var;" is valid in C for some types that are not
  347. # declared (struct something).
  348. # - Using "sizeof(TYPE)" is valid when TYPE is actually a variable.
  349. # - Using the previous two together works reliably.
  350. text = """
  351. %(include)s
  352. %(header)s
  353. int main() {
  354. if ((%(name)s *) 0)
  355. return 0;
  356. if (sizeof (%(name)s))
  357. return 0;
  358. }
  359. """ % { 'include': includetext,
  360. 'header': header,
  361. 'name': type_name }
  362. context.Display("Checking for %s type %s... " % (lang, type_name))
  363. ret = context.BuildProg(text, suffix)
  364. _YesNoResult(context, ret, "HAVE_" + type_name, text,
  365. "Define to 1 if the system has the type `%s'." % type_name)
  366. if ret and fallback and context.headerfilename:
  367. f = open(context.headerfilename, "a")
  368. f.write("typedef %s %s;\n" % (fallback, type_name))
  369. f.close()
  370. return ret
  371. def CheckTypeSize(context, type_name, header = None, language = None, expect = None):
  372. """This check can be used to get the size of a given type, or to check whether
  373. the type is of expected size.
  374. Arguments:
  375. - type : str
  376. the type to check
  377. - includes : sequence
  378. list of headers to include in the test code before testing the type
  379. - language : str
  380. 'C' or 'C++'
  381. - expect : int
  382. if given, will test wether the type has the given number of bytes.
  383. If not given, will automatically find the size.
  384. Returns:
  385. status : int
  386. 0 if the check failed, or the found size of the type if the check succeeded."""
  387. # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
  388. if context.headerfilename:
  389. includetext = '#include "%s"' % context.headerfilename
  390. else:
  391. includetext = ''
  392. if not header:
  393. header = ""
  394. lang, suffix, msg = _lang2suffix(language)
  395. if msg:
  396. context.Display("Cannot check for %s type: %s\n" % (type_name, msg))
  397. return msg
  398. src = includetext + header
  399. if not expect is None:
  400. # Only check if the given size is the right one
  401. context.Display('Checking %s is %d bytes... ' % (type_name, expect))
  402. # test code taken from autoconf: this is a pretty clever hack to find that
  403. # a type is of a given size using only compilation. This speeds things up
  404. # quite a bit compared to straightforward code using TryRun
  405. src = src + r"""
  406. typedef %s scons_check_type;
  407. int main()
  408. {
  409. static int test_array[1 - 2 * !(((long int) (sizeof(scons_check_type))) == %d)];
  410. test_array[0] = 0;
  411. return 0;
  412. }
  413. """
  414. st = context.CompileProg(src % (type_name, expect), suffix)
  415. if not st:
  416. context.Display("yes\n")
  417. _Have(context, "SIZEOF_%s" % type_name, expect,
  418. "The size of `%s', as computed by sizeof." % type_name)
  419. return expect
  420. else:
  421. context.Display("no\n")
  422. _LogFailed(context, src, st)
  423. return 0
  424. else:
  425. # Only check if the given size is the right one
  426. context.Message('Checking size of %s ... ' % type_name)
  427. # We have to be careful with the program we wish to test here since
  428. # compilation will be attempted using the current environment's flags.
  429. # So make sure that the program will compile without any warning. For
  430. # example using: 'int main(int argc, char** argv)' will fail with the
  431. # '-Wall -Werror' flags since the variables argc and argv would not be
  432. # used in the program...
  433. #
  434. src = src + """
  435. #include <stdlib.h>
  436. #include <stdio.h>
  437. int main() {
  438. printf("%d", (int)sizeof(""" + type_name + """));
  439. return 0;
  440. }
  441. """
  442. st, out = context.RunProg(src, suffix)
  443. try:
  444. size = int(out)
  445. except ValueError:
  446. # If cannot convert output of test prog to an integer (the size),
  447. # something went wront, so just fail
  448. st = 1
  449. size = 0
  450. if not st:
  451. context.Display("yes\n")
  452. _Have(context, "SIZEOF_%s" % type_name, size,
  453. "The size of `%s', as computed by sizeof." % type_name)
  454. return size
  455. else:
  456. context.Display("no\n")
  457. _LogFailed(context, src, st)
  458. return 0
  459. return 0
  460. def CheckDeclaration(context, symbol, includes = None, language = None):
  461. """Checks whether symbol is declared.
  462. Use the same test as autoconf, that is test whether the symbol is defined
  463. as a macro or can be used as an r-value.
  464. Arguments:
  465. symbol : str
  466. the symbol to check
  467. includes : str
  468. Optional "header" can be defined to include a header file.
  469. language : str
  470. only C and C++ supported.
  471. Returns:
  472. status : bool
  473. True if the check failed, False if succeeded."""
  474. # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
  475. if context.headerfilename:
  476. includetext = '#include "%s"' % context.headerfilename
  477. else:
  478. includetext = ''
  479. if not includes:
  480. includes = ""
  481. lang, suffix, msg = _lang2suffix(language)
  482. if msg:
  483. context.Display("Cannot check for declaration %s: %s\n" % (symbol, msg))
  484. return msg
  485. src = includetext + includes
  486. context.Display('Checking whether %s is declared... ' % symbol)
  487. src = src + r"""
  488. int main()
  489. {
  490. #ifndef %s
  491. (void) %s;
  492. #endif
  493. ;
  494. return 0;
  495. }
  496. """ % (symbol, symbol)
  497. st = context.CompileProg(src, suffix)
  498. _YesNoResult(context, st, "HAVE_DECL_" + symbol, src,
  499. "Set to 1 if %s is defined." % symbol)
  500. return st
  501. def CheckLib(context, libs, func_name = None, header = None,
  502. extra_libs = None, call = None, language = None, autoadd = 1,
  503. append = True):
  504. """
  505. Configure check for a C or C++ libraries "libs". Searches through
  506. the list of libraries, until one is found where the test succeeds.
  507. Tests if "func_name" or "call" exists in the library. Note: if it exists
  508. in another library the test succeeds anyway!
  509. Optional "header" can be defined to include a header file. If not given a
  510. default prototype for "func_name" is added.
  511. Optional "extra_libs" is a list of library names to be added after
  512. "lib_name" in the build command. To be used for libraries that "lib_name"
  513. depends on.
  514. Optional "call" replaces the call to "func_name" in the test code. It must
  515. consist of complete C statements, including a trailing ";".
  516. Both "func_name" and "call" arguments are optional, and in that case, just
  517. linking against the libs is tested.
  518. "language" should be "C" or "C++" and is used to select the compiler.
  519. Default is "C".
  520. Note that this uses the current value of compiler and linker flags, make
  521. sure $CFLAGS, $CPPFLAGS and $LIBS are set correctly.
  522. Returns an empty string for success, an error message for failure.
  523. """
  524. # Include "confdefs.h" first, so that the header can use HAVE_HEADER_H.
  525. if context.headerfilename:
  526. includetext = '#include "%s"' % context.headerfilename
  527. else:
  528. includetext = ''
  529. if not header:
  530. header = ""
  531. text = """
  532. %s
  533. %s""" % (includetext, header)
  534. # Add a function declaration if needed.
  535. if func_name and func_name != "main":
  536. if not header:
  537. text = text + """
  538. #ifdef __cplusplus
  539. extern "C"
  540. #endif
  541. char %s();
  542. """ % func_name
  543. # The actual test code.
  544. if not call:
  545. call = "%s();" % func_name
  546. # if no function to test, leave main() blank
  547. text = text + """
  548. int
  549. main() {
  550. %s
  551. return 0;
  552. }
  553. """ % (call or "")
  554. if call:
  555. i = call.find("\n")
  556. if i > 0:
  557. calltext = call[:i] + ".."
  558. elif call[-1] == ';':
  559. calltext = call[:-1]
  560. else:
  561. calltext = call
  562. for lib_name in libs:
  563. lang, suffix, msg = _lang2suffix(language)
  564. if msg:
  565. context.Display("Cannot check for library %s: %s\n" % (lib_name, msg))
  566. return msg
  567. # if a function was specified to run in main(), say it
  568. if call:
  569. context.Display("Checking for %s in %s library %s... "
  570. % (calltext, lang, lib_name))
  571. # otherwise, just say the name of library and language
  572. else:
  573. context.Display("Checking for %s library %s... "
  574. % (lang, lib_name))
  575. if lib_name:
  576. l = [ lib_name ]
  577. if extra_libs:
  578. l.extend(extra_libs)
  579. if append:
  580. oldLIBS = context.AppendLIBS(l)
  581. else:
  582. oldLIBS = context.PrependLIBS(l)
  583. sym = "HAVE_LIB" + lib_name
  584. else:
  585. oldLIBS = -1
  586. sym = None
  587. ret = context.BuildProg(text, suffix)
  588. _YesNoResult(context, ret, sym, text,
  589. "Define to 1 if you have the `%s' library." % lib_name)
  590. if oldLIBS != -1 and (ret or not autoadd):
  591. context.SetLIBS(oldLIBS)
  592. if not ret:
  593. return ret
  594. return ret
  595. def CheckProg(context, prog_name):
  596. """
  597. Configure check for a specific program.
  598. Check whether program prog_name exists in path. If it is found,
  599. returns the path for it, otherwise returns None.
  600. """
  601. context.Display("Checking whether %s program exists..." % prog_name)
  602. path = context.env.WhereIs(prog_name)
  603. if path:
  604. context.Display(path + "\n")
  605. else:
  606. context.Display("no\n")
  607. return path
  608. #
  609. # END OF PUBLIC FUNCTIONS
  610. #
  611. def _YesNoResult(context, ret, key, text, comment = None):
  612. """
  613. Handle the result of a test with a "yes" or "no" result.
  614. :Parameters:
  615. - `ret` is the return value: empty if OK, error message when not.
  616. - `key` is the name of the symbol to be defined (HAVE_foo).
  617. - `text` is the source code of the program used for testing.
  618. - `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.
  619. """
  620. if key:
  621. _Have(context, key, not ret, comment)
  622. if ret:
  623. context.Display("no\n")
  624. _LogFailed(context, text, ret)
  625. else:
  626. context.Display("yes\n")
  627. def _Have(context, key, have, comment = None):
  628. """
  629. Store result of a test in context.havedict and context.headerfilename.
  630. :Parameters:
  631. - `key` - is a "HAVE_abc" name. It is turned into all CAPITALS and non-alphanumerics are replaced by an underscore.
  632. - `have` - value as it should appear in the header file, include quotes when desired and escape special characters!
  633. - `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.
  634. The value of "have" can be:
  635. - 1 - Feature is defined, add "#define key".
  636. - 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.
  637. - number - Feature is defined to this number "#define key have". Doesn't work for 0 or 1, use a string then.
  638. - string - Feature is defined to this string "#define key have".
  639. """
  640. key_up = key.upper()
  641. key_up = re.sub('[^A-Z0-9_]', '_', key_up)
  642. context.havedict[key_up] = have
  643. if have == 1:
  644. line = "#define %s 1\n" % key_up
  645. elif have == 0:
  646. line = "/* #undef %s */\n" % key_up
  647. elif isinstance(have, int):
  648. line = "#define %s %d\n" % (key_up, have)
  649. else:
  650. line = "#define %s %s\n" % (key_up, str(have))
  651. if comment is not None:
  652. lines = "\n/* %s */\n" % comment + line
  653. else:
  654. lines = "\n" + line
  655. if context.headerfilename:
  656. f = open(context.headerfilename, "a")
  657. f.write(lines)
  658. f.close()
  659. elif hasattr(context,'config_h'):
  660. context.config_h = context.config_h + lines
  661. def _LogFailed(context, text, msg):
  662. """
  663. Write to the log about a failed program.
  664. Add line numbers, so that error messages can be understood.
  665. """
  666. if LogInputFiles:
  667. context.Log("Failed program was:\n")
  668. lines = text.split('\n')
  669. if len(lines) and lines[-1] == '':
  670. lines = lines[:-1] # remove trailing empty line
  671. n = 1
  672. for line in lines:
  673. context.Log("%d: %s\n" % (n, line))
  674. n = n + 1
  675. if LogErrorMessages:
  676. context.Log("Error message: %s\n" % msg)
  677. def _lang2suffix(lang):
  678. """
  679. Convert a language name to a suffix.
  680. When "lang" is empty or None C is assumed.
  681. Returns a tuple (lang, suffix, None) when it works.
  682. For an unrecognized language returns (None, None, msg).
  683. Where:
  684. - lang = the unified language name
  685. - suffix = the suffix, including the leading dot
  686. - msg = an error message
  687. """
  688. if not lang or lang in ["C", "c"]:
  689. return ("C", ".c", None)
  690. if lang in ["c++", "C++", "cpp", "CXX", "cxx"]:
  691. return ("C++", ".cpp", None)
  692. return None, None, "Unsupported language: %s" % lang
  693. # vim: set sw=4 et sts=4 tw=79 fo+=l:
  694. # Local Variables:
  695. # tab-width:4
  696. # indent-tabs-mode:nil
  697. # End:
  698. # vim: set expandtab tabstop=4 shiftwidth=4: