Enable LTO in CMake with CMAKE_INTERPROCEDURAL_OPTIMIZATION
Turn on link-time optimisation in CMake 3.30 by setting CMAKE_INTERPROCEDURAL_OPTIMIZATION after check_ipo_supported, for GCC and Clang alike.
CMake does not need -flto written into your flags. It has a portable switch, and a helper that checks the compiler supports it before you rely on it.
cmake_minimum_required(VERSION 3.30)
project(app C)
include(CheckIPOSupported)
check_ipo_supported(RESULT ipo_ok OUTPUT ipo_msg LANGUAGES C)
if(ipo_ok)
set(CMAKE_INTERPROCEDURAL_OPTIMIZATION ON)
else()
message(WARNING "LTO not available: ${ipo_msg}")
endif()
add_executable(app main.c util.c)Configuring prints one extra line when the compiler passes the check:
-- IPO / LTO enabledThe ordering is the thing to get right. CMAKE_INTERPROCEDURAL_OPTIMIZATION only initialises the INTERPROCEDURAL_OPTIMIZATION property of targets created after it is set, so putting it below add_executable does nothing and gives no error. For a single target, set the property on the target instead, and use INTERPROCEDURAL_OPTIMIZATION_RELEASE to leave debug builds fast to link.
With GCC, CMake adds -flto and -fno-fat-lto-objects at compile time and passes the flag at link time, and it uses gcc-ar for static libraries so the LTO objects keep their plugin information, which a plain ar would lose. These details are in the CMake property documentation. Expect longer link times and more memory in the link step in exchange for cross-file inlining.