This page covers common configuration steps for CMake.
The main build configuration file:
cmake_minimum_required(VERSION 3.20)
project(MyProject VERSION 1.0.0 LANGUAGES CXX)
# Set C++ standard
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# Add executable
add_executable(myapp src/main.cpp)
# Add libraries
add_library(mylib src/mylib.cpp)
target_include_directories(mylib PUBLIC include)
# Link libraries
target_link_libraries(myapp PRIVATE mylib)
# Installation rules
install(TARGETS myapp DESTINATION bin)
install(TARGETS mylib DESTINATION lib)
Standardized build presets:
{
"version": 3,
"configurePresets": [
{
"name": "default",
"generator": "Ninja",
"binaryDir": "${sourceDir}/build",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"CMAKE_EXPORT_COMPILE_COMMANDS": "ON"
}
},
{
"name": "debug",
"inherits": "default",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug"
}
}
],
"buildPresets": [
{
"name": "default-build",
"configurePreset": "default"
}
],
"testPresets": [
{
"name": "default-test",
"configurePreset": "default"
}
]
}
# Common build types
set(CMAKE_BUILD_TYPE Release) # Optimized build
set(CMAKE_BUILD_TYPE Debug) # Debug build
set(CMAKE_BUILD_TYPE RelWithDebInfo) # Release with debug info
set(CMAKE_BUILD_TYPE MinSizeRel) # Size-optimized
# Add compiler warnings
target_compile_options(myapp PRIVATE -Wall -Wextra -Wpedantic)
# Add definitions
target_compile_definitions(myapp PRIVATE MY_DEFINE=1)
# Add include directories
target_include_directories(myapp PRIVATE include)
# Find packages
find_package(Boost REQUIRED COMPONENTS filesystem)
find_package(OpenSSL REQUIRED)
find_package(Threads REQUIRED)
# Link found packages
target_link_libraries(myapp PRIVATE
Boost::filesystem
OpenSSL::SSL
Threads::Threads
)
# Include CPack module
include(GNUInstallDirs)
include(CPack)
# Package metadata
set(CPACK_PACKAGE_NAME "myapp")
set(CPACK_PACKAGE_VERSION "1.0.0")
set(CPACK_PACKAGE_VENDOR "My Company")
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "My Application")
set(CPACK_PACKAGE_CONTACT "contact@example.com")
# Package-specific settings
set(CPACK_GENERATOR "DEB;RPM")
# DEB specific
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "Maintainer Name")
set(CPACK_DEBIAN_PACKAGE_DEPENDS "libc6 (>= 2.31)")
# RPM specific
set(CPACK_RPM_PACKAGE_LICENSE "MIT")
set(CPACK_RPM_PACKAGE_REQUIRES "glibc >= 2.31")
Re-run CMake after updating configuration:
# Configure
cmake -B build -S .
# Build
cmake --build build
# Package (if CPack configured)
cpack --config build/CPackConfig.cmake
# Check configuration
cmake -L -N
# Show build system info
cmake --build build --target help
# Test build
cmake --build build --target all
Squeezing every bit of performance from your CMake builds? Our experts help with:
Optimize your setup: office@linux-server-admin.com | Contact Us