Skip to content

🎯 CMAKE PRESETS - CONFIGURACIONES PREDEFINIDAS

Qué son los CMake Presets

CMake Presets (CMake 3.19+) son configuraciones predefinidas que simplifican el uso de CMake eliminando la necesidad de recordar flags largos.

Antes (sin presets):

cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug -DENABLE_TESTING=ON -DENABLE_ASAN=ON -DENABLE_UBSAN=ON -G Ninja

Ahora (con presets):

cmake --preset developer


📋 PRESETS DISPONIBLES

🔧 Development Presets

developer ⭐ (Recomendado para desarrollo diario)

cmake --preset developer
cmake --build --preset developer

Incluye: - ✅ Debug build type - ✅ Testing habilitado - ✅ Examples habilitados - ✅ AddressSanitizer (detecta memory bugs) - ✅ UndefinedBehaviorSanitizer (detecta UB) - ✅ Shared libraries (builds más rápidos) - ✅ Compile commands export (para IDEs)

Cuándo usar: Desarrollo diario, debugging, iteración rápida


debug

cmake --preset debug

Incluye: - ✅ Debug build type - ✅ Testing habilitado - ✅ Shared libraries - ❌ Sin sanitizers (más rápido que developer)

Cuándo usar: Debug sin overhead de sanitizers


🚀 Release Presets

release

cmake --preset release
cmake --build --preset release

Incluye: - ✅ Release build type (-O3 optimization) - ✅ Link-Time Optimization (LTO) - ✅ SIMD optimizations (SSE/AVX) - ✅ Precompiled Headers (faster builds) - ✅ Static libraries (single binary)

Cuándo usar: Producción, distribución, benchmarking


release-debug

cmake --preset release-debug

Incluye: - ✅ Release optimizations - ✅ Debug symbols (para profiling) - ✅ LTO + SIMD

Cuándo usar: Profiling, análisis de performance


🤖 CI/CD Presets

ci-linux

cmake --preset ci-linux
cmake --build --preset ci-linux
ctest --preset ci-linux

Incluye: - ✅ Release build - ✅ Testing habilitado - ✅ LTO - ✅ 4 parallel jobs - ✅ Solo para Linux (condition)

Cuándo usar: GitHub Actions, GitLab CI en Linux


ci-windows

cmake --preset ci-windows
cmake --build --preset ci-windows

Incluye: - ✅ Visual Studio 2022 generator - ✅ x64 architecture - ✅ Release build - ✅ Solo para Windows (condition)

Cuándo usar: GitHub Actions, Azure Pipelines en Windows


ci-macos

cmake --preset ci-macos
cmake --build --preset ci-macos

Incluye: - ✅ Universal binary (Intel + Apple Silicon) - ✅ Release build - ✅ Testing habilitado - ✅ Solo para macOS (condition)

Cuándo usar: GitHub Actions en macOS


🔬 Sanitizer Presets

sanitize-address (AddressSanitizer)

cmake --preset sanitize-address
cmake --build --preset sanitize-address
./build/sanitize-address/bin/my_app

Detecta: - ❌ Buffer overflows - ❌ Use-after-free - ❌ Memory leaks - ❌ Double free

Cuándo usar: Testing de seguridad de memoria


sanitize-thread (ThreadSanitizer)

cmake --preset sanitize-thread

Detecta: - ❌ Data races - ❌ Deadlocks - ❌ Thread leaks

Cuándo usar: Testing de multithreading


sanitize-undefined (UBSan)

cmake --preset sanitize-undefined

Detecta: - ❌ Integer overflow - ❌ Null pointer dereference - ❌ Misaligned access - ❌ Undefined behavior


⚡ Special Presets

benchmark

cmake --preset benchmark
cmake --build --preset benchmark

Incluye: - ✅ Full optimization (Release) - ✅ LTO, SIMD, PCH - ✅ Benchmarks habilitados

Cuándo usar: Performance benchmarking


minimal

cmake --preset minimal

Incluye: - ✅ Debug build - ❌ Sin tests, examples, docs, plugins

Cuándo usar: Builds ultra-rápidos para iterar en core code


🚀 USO BÁSICO

Listar Presets Disponibles

# Ver todos los presets
cmake --list-presets

# Ver solo configure presets
cmake --list-presets=configure

# Ver build presets
cmake --list-presets=build

# Ver test presets
cmake --list-presets=test

Workflow Completo con Presets

# 1. Configure
cmake --preset developer

# 2. Build
cmake --build --preset developer

# 3. Test
ctest --preset developer

# O todo junto:
cmake --preset developer && \
  cmake --build --preset developer && \
  ctest --preset developer

🔧 CASOS DE USO COMUNES

Caso 1: Desarrollo Diario

# Setup inicial (una vez)
cmake --preset developer

# Cada vez que editas código
cmake --build --preset developer

# Ejecutar tests
ctest --preset developer

Caso 2: Release Build

# Build optimizado
cmake --preset release
cmake --build --preset release

# Instalar
cmake --install build/release --prefix /usr/local

Caso 3: Debugging Memory Issues

# Build con ASan
cmake --preset sanitize-address
cmake --build --preset sanitize-address

# Ejecutar app (detectará memory bugs)
./build/sanitize-address/bin/my_app

Caso 4: CI/CD Pipeline

# .github/workflows/ci.yml
- name: Configure
  run: cmake --preset ci-${{ matrix.os }}

- name: Build
  run: cmake --build --preset ci-${{ matrix.os }}

- name: Test
  run: ctest --preset ci-${{ matrix.os }}

📝 PERSONALIZAR PRESETS

Crear User Presets (CMakeUserPresets.json)

No editar CMakePresets.json directamente. En su lugar, crea CMakeUserPresets.json (git-ignored):

{
  "version": 6,
  "configurePresets": [
    {
      "name": "my-custom",
      "inherits": "developer",
      "cacheVariables": {
        "MY_CUSTOM_OPTION": "ON",
        "CMAKE_CXX_FLAGS": "-march=native"
      }
    }
  ]
}

Heredar y Extender

{
  "name": "my-release",
  "inherits": "release",
  "cacheVariables": {
    "ENABLE_MY_FEATURE": "ON"
  }
}

🔍 ESTRUCTURA DEL PRESET

Anatomy de un Configure Preset

{
  "name": "developer",                    // Nombre del preset
  "displayName": "Developer",             // Nombre amigable
  "description": "...",                   // Descripción
  "inherits": "base",                     // Hereda de otro preset
  "generator": "Ninja",                   // Generator a usar
  "binaryDir": "build/${presetName}",    // Output directory
  "cacheVariables": {                     // CMake variables
    "CMAKE_BUILD_TYPE": "Debug",
    "ENABLE_TESTING": "ON"
  },
  "condition": {                          // Condicional (ej: solo Linux)
    "type": "equals",
    "lhs": "${hostSystemName}",
    "rhs": "Linux"
  }
}

📊 COMPARACIÓN DE PRESETS

Preset Build Type LTO SIMD Sanitizers Tests Speed Use Case
developer Debug Slow Daily dev
debug Debug Medium Quick debug
release Release Fast Production
release-debug RelWithDebInfo Fast Profiling
minimal Debug Fastest Quick iteration
benchmark Release Fast Benchmarking

💡 TIPS

Tip 1: Preset por Defecto

Agrega a tu shell profile (~/.bashrc, ~/.zshrc):

# Default CMake preset
export CMAKE_PRESET=developer

# Alias
alias cbuild='cmake --build --preset $CMAKE_PRESET'
alias ctest='ctest --preset $CMAKE_PRESET'

Tip 2: Multiple Build Directories

Presets automáticamente crean directorios separados:

cmake --preset developer        # → build/developer/
cmake --preset release          # → build/release/
cmake --preset sanitize-address # → build/sanitize-address/

No hay conflicto entre builds.

Tip 3: CI Matrix

strategy:
  matrix:
    os: [ubuntu-latest, windows-latest, macos-latest]

steps:
  - run: cmake --preset ci-${{ matrix.os }}

🚨 TROUBLESHOOTING

Problema: "Unknown preset"

cmake --preset developer
# CMake Error: No such preset in ...

Solución: Verificar que CMakePresets.json está en la raíz del proyecto:

ls CMakePresets.json

Problema: "CMake version too old"

# CMake Error: CMakePresets.json version 6 requires CMake 3.25+

Solución: Actualizar CMake o reducir version en CMakePresets.json:

{
  "version": 3,  // Requiere CMake 3.20+
  ...
}

Problema: Preset no aparece en --list-presets

Causa: Syntax error en JSON o condition no se cumple

Solución: 1. Validar JSON: jsonlint CMakePresets.json 2. Revisar condition fields (ej: preset solo para Linux)


📚 RECURSOS


🎓 RESUMEN

Para desarrollo diario:

cmake --preset developer
cmake --build --preset developer

Para release:

cmake --preset release
cmake --build --preset release

Para CI/CD:

cmake --preset ci-linux  # o ci-windows, ci-macos

Para debugging:

cmake --preset sanitize-address  # o sanitize-thread, sanitize-undefined


Última actualización: 2025-10-09

Presets simplifican CMake. Úsalos.