CheckAndAddFlag.cmake 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. include(CheckCCompilerFlag)
  2. include(CheckCXXCompilerFlag)
  3. # check_add_add_flag(<variable> <flag> [DEBUG_ONLY | RELEASE_ONLY])
  4. #
  5. # Add a C or C++ compilation flag to the current scope
  6. #
  7. # Can optionally add the flag to Debug or Release configurations only, use this when
  8. # targeting multi-configuration generators like Visual Studio or Xcode.
  9. # Release configurations means NOT Debug, so it will work for RelWithDebInfo or MinSizeRel too.
  10. #
  11. # If the flag is added successfully, the variables FLAG_C_<variable> and FLAG_CXX_<variable>
  12. # may be set to ON.
  13. #
  14. # Examples:
  15. # check_and_add_flag(FOO -foo)
  16. # check_and_add_flag(ONLYDEBUG -onlydebug DEBUG_ONLY)
  17. # check_and_add_flag(OPTMAX -O9001 RELEASE_ONLY)
  18. function(check_and_add_flag var flag)
  19. set(genexp_config_test "1")
  20. if(ARGV2 STREQUAL "DEBUG_ONLY")
  21. set(genexp_config_test "$<CONFIG:Debug>")
  22. elseif(ARGV2 STREQUAL "NO_DEBINFO_ONLY")
  23. set(genexp_config_test "$<NOT:$<OR:$<CONFIG:Debug>,$<CONFIG:RelWithDebInfo>>>")
  24. elseif(ARGV2 STREQUAL "RELEASE_ONLY")
  25. set(genexp_config_test "$<NOT:$<CONFIG:Debug>>")
  26. elseif(ARGV2)
  27. message(FATAL_ERROR "check_and_add_flag called with incorrect arguments: ${ARGN}")
  28. endif()
  29. set(is_c "$<COMPILE_LANGUAGE:C>")
  30. set(is_cxx "$<COMPILE_LANGUAGE:CXX>")
  31. set(test_flags_c)
  32. set(test_flags_cxx)
  33. # The Visual Studio generators don't support COMPILE_LANGUAGE
  34. # So we fail all the C flags and only actually test CXX ones
  35. if(CMAKE_GENERATOR MATCHES "Visual Studio")
  36. set(is_c "0")
  37. set(is_cxx "1")
  38. else()
  39. # Otherwise assume the compile follows GCC syntax
  40. # and fail when the option is known but invalid.
  41. set(test_flags_c "${test_flags_c}-Werror ")
  42. set(test_flags_cxx "${test_flags_cxx}-Werror ")
  43. endif()
  44. check_c_compiler_flag("${test_flags_c}${flag}" FLAG_C_${var})
  45. if(FLAG_C_${var})
  46. add_compile_options("$<$<AND:${is_c},${genexp_config_test}>:${flag}>")
  47. endif()
  48. check_cxx_compiler_flag("${test_flags_cxx}${flag}" FLAG_CXX_${var})
  49. if(FLAG_CXX_${var})
  50. add_compile_options("$<$<AND:${is_cxx},${genexp_config_test}>:${flag}>")
  51. endif()
  52. endfunction()