diff --git a/cmake/modules/AddCompilerFlags.cmake b/cmake/modules/AddCompilerFlags.cmake --- a/cmake/modules/AddCompilerFlags.cmake +++ b/cmake/modules/AddCompilerFlags.cmake @@ -4,7 +4,7 @@ include(SanitizeHelper) function(check_compiler_flag RESULT LANGUAGE FLAG) - sanitize_variable("have_${LANGUAGE}_" ${FLAG} TEST_NAME) + sanitize_c_cxx_definition("have_${LANGUAGE}_" ${FLAG} TEST_NAME) if("${LANGUAGE}" STREQUAL "C") CHECK_C_COMPILER_FLAG(${FLAG} ${TEST_NAME}) @@ -99,7 +99,7 @@ # is a workaround that allow for testing the linker flags. function(add_linker_flag) foreach(f ${ARGN}) - sanitize_variable("have_linker_" ${f} FLAG_IS_SUPPORTED) + sanitize_c_cxx_definition("have_linker_" ${f} FLAG_IS_SUPPORTED) # Some linkers (e.g.: Clang) will issue a -Wunused-command-line-argument # warning when an unknown linker flag is set. diff --git a/cmake/modules/SanitizeHelper.cmake b/cmake/modules/SanitizeHelper.cmake --- a/cmake/modules/SanitizeHelper.cmake +++ b/cmake/modules/SanitizeHelper.cmake @@ -1,3 +1,8 @@ +macro(_sanitize REPLACEMENT_REGEX REPLACEMENT_STRING RAW_VAR SANITIZED_VAR) + string(REGEX REPLACE + "${REPLACEMENT_REGEX}" "${REPLACEMENT_STRING}" ${SANITIZED_VAR} "${RAW_VAR}") +endmacro() + # Sanitize a variable according to cmake rules # https://cmake.org/cmake/help/v3.10/manual/cmake-language.7.html#variable-references # The NUL and ';' characters cannot be escaped in this context (see CMP0053) @@ -14,6 +19,14 @@ # rather to replace them with a known supported one, here '_' is chosen. # Not: this could lead to name collision in some rare case. These case can # be handled manually by using a different prefix. - string(REGEX REPLACE - "([^a-zA-Z0-9/_.+-])" "_" ${SANITIZED_VAR} "${PREFIX}${RAW_VAR}") + _sanitize("([^a-zA-Z0-9/_.+-])" "_" "${PREFIX}${RAW_VAR}" ${SANITIZED_VAR}) +endmacro() + +# Sanitize a variable intended to be used in a C/CXX #define statement. +# This is useful when using CHECK__COMPILER_FLAG or similar functions. +macro(sanitize_c_cxx_definition PREFIX RAW_VAR SANITIZED_VAR) + # Only allow for alphanum chars plus underscore. This will prevent the + # compiler to issue a warning like: + # `ISO C99 requires whitespace after the macro name [-Wc99-extensions]` + _sanitize("([^a-zA-Z0-9_])" "_" "${PREFIX}${RAW_VAR}" ${SANITIZED_VAR}) endmacro()