When building C or C++ applications, improving performance is often a key objective. One effective technique is Link Time Optimization (LTO), which enables the compiler to perform optimizations across translation units during the linking stage. This can result in smaller binaries and faster execution. CMake provides a clean and portable way to enable LTO without complicating the build configuration. This tutorial explains how to enable LTO in CMake.
Consider the following CMakeLists.txt file:
cmake_minimum_required(VERSION 3.27)
project(myapp)
option(ENABLE_LTO "Enable LTO" OFF)
set(CMAKE_CXX_STANDARD 17)
add_executable(${PROJECT_NAME} main.cpp)
if (ENABLE_LTO)
include(CheckIPOSupported)
check_ipo_supported(RESULT LTO_SUPPORTED)
if (LTO_SUPPORTED)
set_property(TARGET ${PROJECT_NAME} PROPERTY INTERPROCEDURAL_OPTIMIZATION TRUE)
endif ()
endif ()
In this setup, the ENABLE_LTO option determines whether LTO is enabled. By default, it is disabled. When enabled, CMake uses the CheckIPOSupported module to verify whether the compiler and linker support LTO.
If support is confirmed, the INTERPROCEDURAL_OPTIMIZATION property is applied to the target. This instructs the compiler to perform LTO during the linking phase, potentially improving runtime performance and reducing binary size.
To configure the project without LTO (default behavior), run:
cmake -S . -B build
To enable LTO during configuration, use:
cmake -S . -B build -DENABLE_LTO=ON
After configuration, build the project with:
cmake --build build
Leave a Comment
Cancel reply