Commit 186a7ba5d71c38e96af07ec9b8dfa29661fabb5a

Patrick Steinhardt 2018-07-19T15:13:40

cmake: error out if required C flags are not supported We do want to notify users compiling our source code early on if they try to use C flags which aren't supported. Add a new macro `AddCFlag`, which results in a fatal error in case the flag is not supported, and use it for our fuzzing flags.

diff --git a/CMakeLists.txt b/CMakeLists.txt
index b976c56..71a79c9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -250,20 +250,25 @@ ELSE()
 ENDIF()
 
 IF(NOT USE_SANITIZER STREQUAL "OFF")
-	SET(CMAKE_C_FLAGS "-fsanitize=${USE_SANITIZER} ${CMAKE_C_FLAGS}")
-	SET(CMAKE_C_FLAGS "-fno-omit-frame-pointer ${CMAKE_C_FLAGS}")
-	SET(CMAKE_C_FLAGS "-fno-optimize-sibling-calls ${CMAKE_C_FLAGS}")
+	# Workaround to force linking against -lasan
+	SET(CMAKE_REQUIRED_FLAGS "-fsanitize=${USE_SANITIZER}")
+	ADD_C_FLAG(-fsanitize=${USE_SANITIZER})
+	UNSET(CMAKE_REQUIRED_FLAGS)
+	ADD_C_FLAG(-fno-omit-frame-pointer)
+	ADD_C_FLAG(-fno-optimize-sibling-calls)
 ENDIF()
 
 IF(USE_COVERAGE)
-	SET(CMAKE_C_FLAGS "-fcoverage-mapping ${CMAKE_C_FLAGS}")
-	SET(CMAKE_C_FLAGS "-fprofile-instr-generate ${CMAKE_C_FLAGS}")
+	ADD_C_FLAG(-fcoverage-mapping)
+	ADD_C_FLAG(-fprofile-instr-generate)
 ENDIF()
 
 IF(BUILD_FUZZERS AND NOT USE_STANDALONE_FUZZERS)
 	# The actual sanitizer link target will be added when linking the fuzz
 	# targets.
-	SET(CMAKE_C_FLAGS "-fsanitize=fuzzer-no-link ${CMAKE_C_FLAGS}")
+	SET(CMAKE_REQUIRED_FLAGS "-fsanitize=fuzzer-no-link")
+	ADD_C_FLAG(-fsanitize=fuzzer-no-link)
+	UNSET(CMAKE_REQUIRED_FLAGS)
 ENDIF ()
 
 ADD_SUBDIRECTORY(src)
diff --git a/cmake/Modules/AddCFlagIfSupported.cmake b/cmake/Modules/AddCFlagIfSupported.cmake
index 67fc895..1d6181c 100644
--- a/cmake/Modules/AddCFlagIfSupported.cmake
+++ b/cmake/Modules/AddCFlagIfSupported.cmake
@@ -5,9 +5,21 @@
 
 INCLUDE(CheckCCompilerFlag)
 
+MACRO(ADD_C_FLAG _FLAG)
+	STRING(TOUPPER ${_FLAG} UPCASE)
+	STRING(REGEX REPLACE "^-" "" UPCASE_PRETTY ${UPCASE})
+	CHECK_C_COMPILER_FLAG(${_FLAG} IS_${UPCASE_PRETTY}_SUPPORTED)
+
+	IF(IS_${UPCASE_PRETTY}_SUPPORTED)
+		SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${_FLAG}")
+	ELSE()
+		MESSAGE(FATAL_ERROR "Required flag ${_FLAG} is not supported")
+	ENDIF()
+ENDMACRO()
+
 MACRO(ADD_C_FLAG_IF_SUPPORTED _FLAG)
 	STRING(TOUPPER ${_FLAG} UPCASE)
-	STRING(REGEX REPLACE "^-" "" UPCASE_PRETTY ${UPCASE}) 
+	STRING(REGEX REPLACE "^-" "" UPCASE_PRETTY ${UPCASE})
 	CHECK_C_COMPILER_FLAG(${_FLAG} IS_${UPCASE_PRETTY}_SUPPORTED)
 
 	IF(IS_${UPCASE_PRETTY}_SUPPORTED)