]> git.ipfire.org Git - thirdparty/xz.git/commitdiff
CMake: Use -O2 instead of -O3 in CMAKE_BUILD_TYPE=Release.
authorLasse Collin <lasse.collin@tukaani.org>
Sat, 17 Feb 2024 19:27:48 +0000 (21:27 +0200)
committerLasse Collin <lasse.collin@tukaani.org>
Mon, 19 Feb 2024 14:28:49 +0000 (16:28 +0200)
-O3 doesn't seem useful for speed but it makes the code bigger.
CMake makes is difficult for users to simply override the
optimization level: CFLAGS / CMAKE_C_FLAGS aren't helpful because
they go before CMAKE_C_FLAGS_RELEASE. Of course, users can override
CMAKE_C_FLAGS_RELEASE directly but then they have to remember to
add also -DNDEBUG to disable assertions.

This commit changes -O3 to -O2 in CMAKE_C_FLAGS_RELEASE if and only if
CMAKE_C_FLAGS_RELEASE cache variable doesn't already exist. So if
a custom value is passed on the command line (or reconfiguring an
already-configured build), the cache variable won't be modified.

CMakeLists.txt

index 19ae4814717a274aee5bd5871bce0414abe8464d..9716f3506f19ec189a57f6eca4179673df4c5de9 100644 (file)
@@ -74,9 +74,28 @@ string(REGEX REPLACE
 .*$"
        "\\1.\\2.\\3" PACKAGE_VERSION "${PACKAGE_VERSION}")
 
+# With several compilers, CMAKE_BUILD_TYPE=Release uses -O3 optimization
+# which results in bigger code without a clear difference in speed. If
+# no user-defined CMAKE_C_FLAGS_RELEASE is present, override -O3 to -O2
+# to make it possible to recommend CMAKE_BUILD_TYPE=Release.
+if(NOT DEFINED CMAKE_C_FLAGS_RELEASE)
+    set(OVERRIDE_O3_IN_C_FLAGS_RELEASE ON)
+endif()
+
 # Among other things, this gives us variables xz_VERSION and xz_VERSION_MAJOR.
 project(xz VERSION "${PACKAGE_VERSION}" LANGUAGES C)
 
+if(OVERRIDE_O3_IN_C_FLAGS_RELEASE)
+    # Looking at CMake's source, there aren't any _FLAGS_RELEASE_INIT
+    # entries where "-O3" would appear as part of some other option,
+    # thus a simple search and replace should be fine.
+    string(REPLACE -O3 -O2 CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE}")
+
+    # Update the cache value while keeping its docstring unchanged.
+    set_property(CACHE CMAKE_C_FLAGS_RELEASE
+                 PROPERTY VALUE "${CMAKE_C_FLAGS_RELEASE}")
+endif()
+
 # We need a compiler that supports enough C99 or newer (variable-length arrays
 # aren't needed, those are optional in C17). Setting CMAKE_C_STANDARD here
 # makes it the default for all targets. It doesn't affect the INTERFACE so