CheckCCompilerFlag.cmake 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. # file Copyright.txt or https://cmake.org/licensing for details.
  3. #[=======================================================================[.rst:
  4. CheckCCompilerFlag
  5. ------------------
  6. Check whether the C compiler supports a given flag.
  7. .. command:: check_c_compiler_flag
  8. .. code-block:: cmake
  9. check_c_compiler_flag(<flag> <var>)
  10. Check that the ``<flag>`` is accepted by the compiler without
  11. a diagnostic. Stores the result in an internal cache entry
  12. named ``<var>``.
  13. This command temporarily sets the ``CMAKE_REQUIRED_DEFINITIONS`` variable
  14. and calls the ``check_c_source_compiles`` macro from the
  15. :module:`CheckCSourceCompiles` module. See documentation of that
  16. module for a listing of variables that can otherwise modify the build.
  17. A positive result from this check indicates only that the compiler did not
  18. issue a diagnostic message when given the flag. Whether the flag has any
  19. effect or even a specific one is beyond the scope of this module.
  20. .. note::
  21. Since the :command:`try_compile` command forwards flags from variables
  22. like :variable:`CMAKE_C_FLAGS <CMAKE_<LANG>_FLAGS>`, unknown flags
  23. in such variables may cause a false negative for this check.
  24. #]=======================================================================]
  25. include_guard(GLOBAL)
  26. include(CheckCSourceCompiles)
  27. include(CMakeCheckCompilerFlagCommonPatterns)
  28. macro (CHECK_C_COMPILER_FLAG _FLAG _RESULT)
  29. set(SAFE_CMAKE_REQUIRED_DEFINITIONS "${CMAKE_REQUIRED_DEFINITIONS}")
  30. set(CMAKE_REQUIRED_DEFINITIONS "${_FLAG}")
  31. # Normalize locale during test compilation.
  32. set(_CheckCCompilerFlag_LOCALE_VARS LC_ALL LC_MESSAGES LANG)
  33. foreach(v ${_CheckCCompilerFlag_LOCALE_VARS})
  34. set(_CheckCCompilerFlag_SAVED_${v} "$ENV{${v}}")
  35. set(ENV{${v}} C)
  36. endforeach()
  37. CHECK_COMPILER_FLAG_COMMON_PATTERNS(_CheckCCompilerFlag_COMMON_PATTERNS)
  38. CHECK_C_SOURCE_COMPILES("int main(void) { return 0; }" ${_RESULT}
  39. # Some compilers do not fail with a bad flag
  40. FAIL_REGEX "command line option .* is valid for .* but not for C" # GNU
  41. ${_CheckCCompilerFlag_COMMON_PATTERNS}
  42. )
  43. foreach(v ${_CheckCCompilerFlag_LOCALE_VARS})
  44. set(ENV{${v}} ${_CheckCCompilerFlag_SAVED_${v}})
  45. unset(_CheckCCompilerFlag_SAVED_${v})
  46. endforeach()
  47. unset(_CheckCCompilerFlag_LOCALE_VARS)
  48. unset(_CheckCCompilerFlag_COMMON_PATTERNS)
  49. set (CMAKE_REQUIRED_DEFINITIONS "${SAFE_CMAKE_REQUIRED_DEFINITIONS}")
  50. endmacro ()