← Back to team overview

kicad-developers team mailing list archive

[PATCH 2/2] Use Link Time Optimization with GCC in Release builds

 

This significantly reduces executable file size, and should also improve
performance.
---
 CMakeLists.txt                          | 15 +++++++++++++++
 CMakeModules/PerformFeatureChecks.cmake |  1 +
 2 files changed, 16 insertions(+)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index ea19617..f6bb20b 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -160,6 +160,21 @@ if( CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang" )
         set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fvisibility-inlines-hidden" )
     endif()
 
+    if( CMAKE_BUILD_TYPE MATCHES Release AND GXX_HAS_LTO_FLAG )
+        find_program(CMAKE_GCC_AR NAMES ${_CMAKE_TOOLCHAIN_PREFIX}gcc-ar${_CMAKE_TOOLCHAIN_SUFFIX} HINTS ${_CMAKE_TOOLCHAIN_LOCATION})
+        find_program(CMAKE_GCC_NM NAMES ${_CMAKE_TOOLCHAIN_PREFIX}gcc-nm HINTS ${_CMAKE_TOOLCHAIN_LOCATION})
+        find_program(CMAKE_GCC_RANLIB NAMES ${_CMAKE_TOOLCHAIN_PREFIX}gcc-ranlib HINTS ${_CMAKE_TOOLCHAIN_LOCATION})
+
+        if( CMAKE_GCC_AR AND CMAKE_GCC_NM AND CMAKE_GCC_RANLIB )
+            set( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -flto -fno-fat-lto-objects" )
+            set( CMAKE_AR "${CMAKE_GCC_AR}" )
+            set( CMAKE_NM "${CMAKE_GCC_NM}" )
+            set( CMAKE_RANLIB "${CMAKE_GCC_RANLIB}" )
+        else()
+            message( WARNING "GCC indicates LTO support, but binutils wrappers could not be found. Disabling LTO." )
+        endif()
+    endif()
+
     find_package( OpenMP QUIET )
 
     if( OPENMP_FOUND )
diff --git a/CMakeModules/PerformFeatureChecks.cmake b/CMakeModules/PerformFeatureChecks.cmake
index b48cb0a..ae6d561 100644
--- a/CMakeModules/PerformFeatureChecks.cmake
+++ b/CMakeModules/PerformFeatureChecks.cmake
@@ -49,6 +49,7 @@ macro( perform_feature_checks )
 
     check_cxx_compiler_flag( -fvisibility=hidden GXX_HAS_VISIBILITY_FLAG )
     check_cxx_compiler_flag( -fvisibility-inlines-hidden GXX_HAS_VISIBILITY_INLINES_FLAG )
+    check_cxx_compiler_flag( -flto GXX_HAS_LTO_FLAG )
 
     check_include_file( "malloc.h" HAVE_MALLOC_H )
 

References