From 59bc36a537c33c1ddf6f689aee4c790e69b4b2c4 Mon Sep 17 00:00:00 2001
From: Martin Stump <martin.stump@mercedes-benz.com>
Date: Fri, 25 Nov 2022 09:49:00 +0100
Subject: [PATCH] Check if compiler supports a flag before adding

Signed-off-by: Martin Stump <martin.stump@mercedes-benz.com>
---
 CMakeLists.txt | 26 +++++++++++++++++++++-----
 1 file changed, 21 insertions(+), 5 deletions(-)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5fb90ff..454acaf 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -29,7 +29,7 @@ project(
   LANGUAGES CXX
 )
 
-# Options that control generation of various targets.
+# Add project options
 option(MantleAPI_DOC "Generate the doc target." ${MantleAPI_MAIN_PROJECT})
 option(MantleAPI_INSTALL "Generate the install target." ${MantleAPI_MAIN_PROJECT})
 option(MantleAPI_TEST "Generate the test target." ${MantleAPI_MAIN_PROJECT})
@@ -37,22 +37,38 @@ option(MantleAPI_PACKAGE "Generate the package target." ${MantleAPI_MAIN_PROJECT
 option(MantleAPI_ENABLE_WARNINGS "Enable compiler warnings." ${MantleAPI_MAIN_PROJECT})
 option(MantleAPI_ENABLE_WERROR "Fail and stop if a warning is triggered." ${MantleAPI_MAIN_PROJECT})
 
+# Add compiler flags
+include(CheckCXXCompilerFlag)
+function(add_cxx_compiler_flag)
+  string(TOUPPER ${ARGV0} IDENTIFIER)
+  string(REGEX REPLACE "^[^A-Z0-9]" "" IDENTIFIER ${IDENTIFIER})
+  string(MAKE_C_IDENTIFIER ${IDENTIFIER} IDENTIFIER)
+  check_cxx_compiler_flag(${ARGV0} HAVE_${IDENTIFIER})
+  if(${HAVE_${IDENTIFIER}})
+    add_compile_options(${ARGV0})
+  endif()
+endfunction()
+
 if(MSVC)
   if(MantleAPI_ENABLE_WARNINGS)
-    add_compile_options(/W4)
+    add_cxx_compiler_flag(/W4)
   endif()
   if(MantleAPI_ENABLE_WERROR)
-    add_compile_options(/WX /wd4996)
+    add_cxx_compiler_flag(/WX)
+    add_cxx_compiler_flag(/wd4996)
   endif()
 else()
   if(MantleAPI_ENABLE_WARNINGS)
-    add_compile_options(-Wall -Wextra)
+    add_cxx_compiler_flag(-Wall)
+    add_cxx_compiler_flag(-Wextra)
   endif()
   if(MantleAPI_ENABLE_WERROR)
-    add_compile_options(-Werror -Wno-error=deprecated-declarations)
+    add_cxx_compiler_flag(-Werror)
+    add_cxx_compiler_flag(-Wno-error=deprecated-declarations)
   endif()
 endif()
 
+# Add CPM.cmake
 include(CPM)
 
 add_subdirectory(include)
-- 
GitLab