NetdataCompilerFlags.cmake 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Functions to simplify handling of extra compiler flags.
  2. #
  3. # Copyright (c) 2024 Netdata Inc.
  4. # SPDX-License-Identifier: GPL-3.0-or-later
  5. include(CheckCCompilerFlag)
  6. include(CheckCXXCompilerFlag)
  7. # Construct a pre-processor safe name
  8. #
  9. # This takes a specified value, and assigns the generated name to the
  10. # specified target.
  11. function(make_cpp_safe_name value target)
  12. string(REPLACE "-" "_" tmp "${value}")
  13. string(REPLACE "=" "_" tmp "${tmp}")
  14. set(${target} "${tmp}" PARENT_SCOPE)
  15. endfunction()
  16. # Conditionally add an extra compiler flag to C and C++ flags.
  17. #
  18. # If the language flags already match the `match` argument, skip this flag.
  19. # Otherwise, check for support for `flag` and if support is found, add it to
  20. # the language-specific `target` flag group.
  21. function(add_simple_extra_compiler_flag match flag target)
  22. set(CMAKE_REQUIRED_FLAGS "-Werror")
  23. make_cpp_safe_name("${flag}" flag_name)
  24. if(NOT ${CMAKE_C_FLAGS} MATCHES ${match})
  25. check_c_compiler_flag("${flag}" HAVE_C_${flag_name})
  26. if(HAVE_C_${flag_name})
  27. set(${target}_C_FLAGS "${${target}_C_FLAGS} ${flag}" PARENT_SCOPE)
  28. endif()
  29. endif()
  30. if(NOT ${CMAKE_CXX_FLAGS} MATCHES ${match})
  31. check_cxx_compiler_flag("${flag}" HAVE_CXX_${flag_name})
  32. if(HAVE_CXX_${flag_name})
  33. set(${target}_CXX_FLAGS "${${target}_CXX_FLAGS} ${flag}" PARENT_SCOPE)
  34. endif()
  35. endif()
  36. endfunction()
  37. # Same as add_simple_extra_compiler_flag, but check for a second flag if the
  38. # first one is unsupported.
  39. function(add_double_extra_compiler_flag match flag1 flag2 target)
  40. set(CMAKE_REQUIRED_FLAGS "-Werror")
  41. make_cpp_safe_name("${flag1}" flag1_name)
  42. make_cpp_safe_name("${flag2}" flag2_name)
  43. if(NOT ${CMAKE_C_FLAGS} MATCHES ${match})
  44. check_c_compiler_flag("${flag1}" HAVE_C_${flag1_name})
  45. if(HAVE_C_${flag1_name})
  46. set(${target}_C_FLAGS "${${target}_C_FLAGS} ${flag1}" PARENT_SCOPE)
  47. else()
  48. check_c_compiler_flag("${flag2}" HAVE_C_${flag2_name})
  49. if(HAVE_C_${flag2_name})
  50. set(${target}_C_FLAGS "${${target}_C_FLAGS} ${flag2}" PARENT_SCOPE)
  51. endif()
  52. endif()
  53. endif()
  54. if(NOT ${CMAKE_CXX_FLAGS} MATCHES ${match})
  55. check_cxx_compiler_flag("${flag1}" HAVE_CXX_${flag1_name})
  56. if(HAVE_CXX_${flag1_name})
  57. set(${target}_CXX_FLAGS "${${target}_CXX_FLAGS} ${flag1}" PARENT_SCOPE)
  58. else()
  59. check_cxx_compiler_flag("${flag2}" HAVE_CXX_${flag2_name})
  60. if(HAVE_CXX_${flag2_name})
  61. set(${target}_CXX_FLAGS "${${target}_CXX_FLAGS} ${flag2}" PARENT_SCOPE)
  62. endif()
  63. endif()
  64. endif()
  65. endfunction()