Commit 77822ed1664a4e58915826001c401e8cadafb995

Anonymous Maarten 2022-10-05T15:14:08

cmake: add SDL_WERROR to conditionally enable/disable -Werror

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 5867e5b..aba7bf9 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -509,6 +509,8 @@ dep_option(SDL_HIDAPI_JOYSTICK     "Use HIDAPI for low level joystick drivers" O
 dep_option(SDL_VIRTUAL_JOYSTICK    "Enable the virtual-joystick driver" ON SDL_HIDAPI OFF)
 set_option(SDL_ASAN                "Use AddressSanitizer to detect memory errors" OFF)
 
+option(SDL_WERROR "Enable -Werror" OFF)
+
 option(SDL_SHARED "Build a shared version of the library" ${SDL_SHARED_ENABLED_BY_DEFAULT})
 option(SDL_STATIC "Build a static version of the library" ${SDL_STATIC_ENABLED_BY_DEFAULT})
 option(SDL_TEST   "Build the SDL2_test library" ${SDL_TEST_ENABLED_BY_DEFAULT})
@@ -519,6 +521,26 @@ set_option(SDL_INSTALL_TESTS   "Install test-cases" OFF)
 
 set(HAVE_STATIC_PIC "${SDL_STATIC_PIC}")
 
+if(SDL_WERROR)
+  if(MSVC)
+    cmake_push_check_state(RESET)
+    check_c_compiler_flag(/WX HAVE_WX)
+    if(HAVE_WX)
+      set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} /WX")
+      set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /WX")
+    endif()
+  elseif(USE_GCC OR USE_CLANG)
+    cmake_push_check_state(RESET)
+    check_c_compiler_flag(-Werror HAVE_WERROR)
+    if(HAVE_WERROR)
+      set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Werror")
+      set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
+      set(CMAKE_OBJC_FLAGS "${CMAKE_OBJC_FLAGS} -Werror")
+    endif()
+    cmake_pop_check_state()
+  endif()
+endif()
+
 if(SDL_HIDAPI)
   if(HIDAPI_ONLY_LIBUSB)
     set(SDL_HIDAPI_LIBUSB ON CACHE BOOL "" FORCE)
@@ -606,9 +628,11 @@ if(USE_GCC OR USE_CLANG)
 
   check_c_compiler_flag(-Wdeclaration-after-statement HAVE_GCC_WDECLARATION_AFTER_STATEMENT)
   if(HAVE_GCC_WDECLARATION_AFTER_STATEMENT)
-    check_c_compiler_flag(-Werror=declaration-after-statement HAVE_GCC_WERROR_DECLARATION_AFTER_STATEMENT)
-    if(HAVE_GCC_WERROR_DECLARATION_AFTER_STATEMENT)
-      list(APPEND EXTRA_CFLAGS "-Werror=declaration-after-statement")
+    if(SDL_WERROR)
+      check_c_compiler_flag(-Werror=declaration-after-statement HAVE_GCC_WERROR_DECLARATION_AFTER_STATEMENT)
+      if(HAVE_GCC_WERROR_DECLARATION_AFTER_STATEMENT)
+        list(APPEND EXTRA_CFLAGS "-Werror=declaration-after-statement")
+      endif()
     endif()
     list(APPEND EXTRA_CFLAGS "-Wdeclaration-after-statement")
   endif()