Skip to content

⚡ CMAKE CHEAT SHEET - AUDIOLAB

Quick Reference de Comandos CMake Esenciales

Bookmarkea esta página para consultas rápidas durante desarrollo


📋 TABLA DE CONTENIDOS

  1. Comandos Básicos
  2. Configuración
  3. Building
  4. Targets
  5. Testing
  6. Installation
  7. Variables Útiles
  8. Generator Expressions
  9. Debugging
  10. CMake en CI/CD

🔧 COMANDOS BÁSICOS

Workflow Estándar

# 1. Configure
cmake -S <source-dir> -B <build-dir> [options]

# 2. Build
cmake --build <build-dir> [--config <config>] [--target <target>]

# 3. Test (opcional)
ctest --test-dir <build-dir>

# 4. Install (opcional)
cmake --install <build-dir>

Ejemplos Comunes

# Build simple
cmake -S . -B build
cmake --build build

# Con configuración específica
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build --config Release

# Paralelismo
cmake --build build -j 8          # 8 cores
cmake --build build -j $(nproc)   # Todos los cores (Linux)

# Verbose (ver comandos ejecutados)
cmake --build build --verbose
cmake --build build -v

⚙️ CONFIGURACIÓN

Build Types

# Debug (símbolos debug, sin optimización)
cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug

# Release (optimización máxima, sin debug)
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release

# RelWithDebInfo (optimizado + símbolos debug)
cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo

# MinSizeRel (optimizado para tamaño)
cmake -S . -B build -DCMAKE_BUILD_TYPE=MinSizeRel

Generators

# Ninja (recomendado - más rápido)
cmake -S . -B build -G Ninja

# Unix Makefiles (default en Linux/macOS)
cmake -S . -B build -G "Unix Makefiles"

# Visual Studio 2022
cmake -S . -B build -G "Visual Studio 17 2022" -A x64

# Xcode
cmake -S . -B build -G Xcode

# Listar generators disponibles
cmake --help

Especificar Compilador

# GCC
cmake -S . -B build -DCMAKE_CXX_COMPILER=g++

# Clang
cmake -S . -B build -DCMAKE_CXX_COMPILER=clang++

# Versión específica
cmake -S . -B build -DCMAKE_CXX_COMPILER=g++-11

# MSVC (Windows)
cmake -S . -B build -T v143  # VS 2022 toolset

# Con toolchain file
cmake -S . -B build -DCMAKE_TOOLCHAIN_FILE=path/to/toolchain.cmake

Variables de Configuración

# Set variable
cmake -S . -B build -DVAR_NAME=VALUE

# Multiple variables
cmake -S . -B build \
      -DCMAKE_BUILD_TYPE=Release \
      -DENABLE_TESTING=ON \
      -DBUILD_SHARED_LIBS=ON

# Boolean variables
cmake -S . -B build -DENABLE_FEATURE=ON   # o OFF

# String variables
cmake -S . -B build -DPROJECT_VERSION="1.0.0"

# Path variables
cmake -S . -B build -DCMAKE_INSTALL_PREFIX=/usr/local

🔨 BUILDING

Build Commands

# Build all targets
cmake --build build

# Build specific target
cmake --build build --target my_target

# Build with config (multi-config generators)
cmake --build build --config Release

# Clean before build
cmake --build build --clean-first

# Parallel build
cmake --build build -j 8
cmake --build build --parallel 8

Build Targets Especiales

# Build all
cmake --build build --target all

# Clean (remove build artifacts)
cmake --build build --target clean

# Install
cmake --build build --target install

# Run tests
cmake --build build --target test

🎯 TARGETS

Listar Targets Disponibles

# Con Makefile generator
make -C build help

# Con Ninja
ninja -C build -t targets

# Con cualquier generator (CMake 3.7+)
cmake --build build --target help

Build de Targets Individuales

# Librerías
cmake --build build --target audiolab_core
cmake --build build --target audiolab_dsp

# Ejecutables
cmake --build build --target audiolab_app
cmake --build build --target audiolab_tests

# Plugins
cmake --build build --target reverb_vst3
cmake --build build --target delay_vst3

🧪 TESTING

Ejecutar Tests

# Todos los tests
ctest --test-dir build

# Con output detallado
ctest --test-dir build --verbose
ctest --test-dir build --output-on-failure

# Tests específicos
ctest --test-dir build -R "test_name_regex"

# Excluir tests
ctest --test-dir build -E "test_name_regex"

# Parallel testing
ctest --test-dir build -j 8

# Repeat tests (para flaky tests)
ctest --test-dir build --repeat until-pass:3

# Mostrar solo failures
ctest --test-dir build --output-on-failure --stop-on-failure

Testing con Labels

# Run tests con label específico
ctest --test-dir build -L unit
ctest --test-dir build -L integration
ctest --test-dir build -L performance

📦 INSTALLATION

Install Commands

# Install a location default
cmake --install build

# Install a location custom
cmake --install build --prefix /custom/path

# Install con config específico
cmake --install build --config Release

# Install solo componente específico
cmake --install build --component Runtime

Install Destinations

# Configurar prefix durante configure
cmake -S . -B build -DCMAKE_INSTALL_PREFIX=/usr/local

# Paths de instalación
# Binarios: ${CMAKE_INSTALL_PREFIX}/bin
# Libs: ${CMAKE_INSTALL_PREFIX}/lib
# Headers: ${CMAKE_INSTALL_PREFIX}/include
# Data: ${CMAKE_INSTALL_PREFIX}/share

🔑 VARIABLES ÚTILES

Variables de Sistema

# Build type
-DCMAKE_BUILD_TYPE=Debug|Release|RelWithDebInfo|MinSizeRel

# Compiler
-DCMAKE_CXX_COMPILER=/path/to/compiler
-DCMAKE_C_COMPILER=/path/to/c-compiler

# Compiler flags
-DCMAKE_CXX_FLAGS="-Wall -Wextra"
-DCMAKE_CXX_FLAGS_DEBUG="-g -O0"
-DCMAKE_CXX_FLAGS_RELEASE="-O3 -DNDEBUG"

# Linker flags
-DCMAKE_EXE_LINKER_FLAGS="-Wl,--as-needed"

# Install prefix
-DCMAKE_INSTALL_PREFIX=/usr/local

# Find packages path
-DCMAKE_PREFIX_PATH="/path/to/deps1;/path/to/deps2"

# Build shared/static libs
-DBUILD_SHARED_LIBS=ON|OFF

# Position independent code
-DCMAKE_POSITION_INDEPENDENT_CODE=ON

# Export compile commands (for IDEs)
-DCMAKE_EXPORT_COMPILE_COMMANDS=ON

# Color diagnostics
-DCMAKE_COLOR_DIAGNOSTICS=ON

Variables de Proyecto (AudioLab)

# AudioLab specific
-DENABLE_LTO=ON              # Link-Time Optimization
-DENABLE_SIMD=ON             # SIMD optimizations (SSE/AVX)
-DENABLE_PCH=ON              # Precompiled Headers
-DENABLE_TESTING=ON          # Build tests
-DENABLE_EXAMPLES=ON         # Build examples
-DENABLE_DOCS=ON             # Build documentation

# Sanitizers
-DENABLE_ASAN=ON             # AddressSanitizer
-DENABLE_UBSAN=ON            # UndefinedBehaviorSanitizer
-DENABLE_TSAN=ON             # ThreadSanitizer
-DENABLE_MSAN=ON             # MemorySanitizer

# Build options
-DBUILD_VST3=ON              # Build VST3 plugins
-DBUILD_AU=ON                # Build AudioUnit plugins
-DBUILD_STANDALONE=ON        # Build standalone apps

💡 GENERATOR EXPRESSIONS

Generator expressions se evalúan durante generación, útiles para flags condicionales:

# Compilar flags por configuración
target_compile_options(my_target PRIVATE
    $<$<CONFIG:Debug>:-g -O0>
    $<$<CONFIG:Release>:-O3 -DNDEBUG>
)

# Compilar flags por compilador
target_compile_options(my_target PRIVATE
    $<$<CXX_COMPILER_ID:GNU>:-Wall -Wextra>
    $<$<CXX_COMPILER_ID:MSVC>:/W4>
)

# Linker flags condicionales
target_link_options(my_target PRIVATE
    $<$<PLATFORM_ID:Linux>:-Wl,--as-needed>
    $<$<PLATFORM_ID:Darwin>:-dead_strip>
)

# Include directories por target
target_include_directories(my_target PUBLIC
    $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
    $<INSTALL_INTERFACE:include>
)

🐛 DEBUGGING

Debug CMake Configuration

# Ver variables definidas
cmake -S . -B build -L         # Lista variables cache
cmake -S . -B build -LA        # Lista todas (include advanced)
cmake -S . -B build -LAH       # Lista con help strings

# Trace durante configure
cmake -S . -B build --trace
cmake -S . -B build --trace-expand
cmake -S . -B build --trace-source=CMakeLists.txt

# Debug find_package
cmake -S . -B build --debug-find
cmake -S . -B build --debug-find-pkg=JUCE

# Verbose makefile
cmake -S . -B build -DCMAKE_VERBOSE_MAKEFILE=ON

# Warn unused variables
cmake -S . -B build --warn-unused-vars

Inspeccionar Build

# Ver comandos exactos de compilación
cmake --build build --verbose

# Generar compile_commands.json (para IDEs)
cmake -S . -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON

# Ver targets y propiedades
cmake --build build --target help

CMake Messages en CMakeLists.txt

# Print variables
message(STATUS "Build type: ${CMAKE_BUILD_TYPE}")
message(WARNING "This is a warning")
message(FATAL_ERROR "This stops configuration")

# Debug variable
message(STATUS "MY_VAR = ${MY_VAR}")

# Print all variables
get_cmake_property(_vars VARIABLES)
foreach(_var ${_vars})
    message(STATUS "${_var} = ${${_var}}")
endforeach()

🚀 CMAKE EN CI/CD

GitHub Actions Example

- name: Configure CMake
  run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Release

- name: Build
  run: cmake --build build --config Release -j 4

- name: Test
  run: ctest --test-dir build --output-on-failure

- name: Install
  run: cmake --install build --prefix install-dir

Build Matrix (Multiple Configs)

# Script para CI
for config in Debug Release RelWithDebInfo; do
    cmake -S . -B build-$config -DCMAKE_BUILD_TYPE=$config
    cmake --build build-$config -j $(nproc)
    ctest --test-dir build-$config --output-on-failure
done

📚 PRESETS (CMake 3.19+)

Usar Presets

# Listar presets disponibles
cmake --list-presets

# Configure con preset
cmake --preset developer
cmake --preset ci-linux
cmake --preset release

# Build con preset
cmake --build --preset developer

# Test con preset
ctest --preset developer

CMakePresets.json Example

{
  "version": 3,
  "configurePresets": [
    {
      "name": "developer",
      "binaryDir": "build",
      "cacheVariables": {
        "CMAKE_BUILD_TYPE": "Debug",
        "ENABLE_TESTING": "ON"
      }
    },
    {
      "name": "release",
      "binaryDir": "build-release",
      "cacheVariables": {
        "CMAKE_BUILD_TYPE": "Release",
        "ENABLE_LTO": "ON"
      }
    }
  ]
}

🔧 CASOS DE USO COMUNES

Caso 1: Development Build

cmake -S . -B build \
      -DCMAKE_BUILD_TYPE=Debug \
      -DCMAKE_EXPORT_COMPILE_COMMANDS=ON \
      -DENABLE_TESTING=ON \
      -DENABLE_ASAN=ON

cmake --build build -j $(nproc)

Caso 2: Release Build Optimizado

cmake -S . -B build-release \
      -DCMAKE_BUILD_TYPE=Release \
      -DENABLE_LTO=ON \
      -DENABLE_SIMD=ON \
      -DENABLE_PCH=ON

cmake --build build-release -j $(nproc)
cmake --install build-release --prefix /usr/local

Caso 3: Cross-Compilation

cmake -S . -B build-windows \
      -DCMAKE_TOOLCHAIN_FILE=toolchains/mingw-w64.cmake \
      -DCMAKE_BUILD_TYPE=Release

cmake --build build-windows

Caso 4: Incremental Build (después de cambiar código)

# Solo rebuild lo que cambió
cmake --build build

# Rebuild target específico
cmake --build build --target my_modified_target

Caso 5: Clean Rebuild

# Opción 1: Clean + build
cmake --build build --clean-first

# Opción 2: Borrar y reconfigurar
rm -rf build
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build

🎨 TIPS Y TRICKS

Acelerar Builds

# 1. Usar Ninja
cmake -G Ninja -S . -B build

# 2. Precompiled Headers
cmake -S . -B build -DENABLE_PCH=ON

# 3. ccache
cmake -S . -B build -DCMAKE_CXX_COMPILER_LAUNCHER=ccache

# 4. Parallel jobs
cmake --build build -j $(nproc)

# 5. Unity builds (combina .cpp files)
cmake -S . -B build -DCMAKE_UNITY_BUILD=ON

Ver Tiempo de Build

# Unix/macOS
time cmake --build build

# Con breakdown por target (Ninja)
ninja -C build -d stats

Limpiar Caches

# Borrar CMakeCache.txt (reconfigurar desde cero)
rm build/CMakeCache.txt

# Borrar todo el build directory
rm -rf build

⚠️ ERRORES COMUNES Y SOLUCIONES

# Error: "CMake Error: The source directory does not exist"
# Solución: Verificar path, usar -S y -B correctamente
cmake -S . -B build  # Correcto

# Error: "No CMAKE_CXX_COMPILER could be found"
# Solución: Instalar compilador o especificarlo
cmake -S . -B build -DCMAKE_CXX_COMPILER=g++

# Error: "Could not find a package configuration file"
# Solución: Especificar CMAKE_PREFIX_PATH
cmake -S . -B build -DCMAKE_PREFIX_PATH=/path/to/deps

# Error: "Ninja: build stopped: subcommand failed"
# Solución: Rebuild con verbose para ver error
cmake --build build --verbose

# Error: Build muy lento
# Solución: Usar Ninja y parallel jobs
cmake -G Ninja -S . -B build
cmake --build build -j $(nproc)

📖 RECURSOS

Documentación Oficial

AudioLab Docs


💡 TIP: Imprime esta página o guárdala como PDF para referencia rápida.

Última actualización: 2025-10-09