3 Commits
Author SHA1 Message Date
Student 63ddb070d5 VulkanSDK 2026-10-15 11:14:14 +07:00
Student 7467219709 ps1 2026-10-15 10:12:27 +07:00
Student 57463dc219 Initial commit 2026-10-15 09:59:40 +07:00
9122 changed files with 1808768 additions and 55 deletions

No files matched your search

+15 -24
View File
@@ -4,12 +4,6 @@ project(Xenith)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
# ---------------------------------------------------------------------------
# Тип сборки по умолчанию — Release.
# Без этого `cmake -B build` без -DCMAKE_BUILD_TYPE не выполняет ни Debug-,
# ни Release-ветку, и проект собирается на -O0 молча. А в Debug-ветке раньше
# включались санитайзеры, из-за чего в релизы попадал 50-мегабайтный ASAN-бинарник.
# ---------------------------------------------------------------------------
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE Release CACHE STRING "Тип сборки" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS Release Debug RelWithDebInfo)
@@ -85,23 +79,11 @@ set(SOURCES
xenith/ollama_api/handler.cpp
)
# НЕ собираются намеренно:
# xenith/ollama_api/test.cpp — в нём собственный main() → duplicate symbol.
# Собирается отдельным таргетом xenith_ollama_mock.
# xenith/preprocessing/tokenizer.cpp, xenith/converter.cpp
# — мёртвое ядро старого формата .bfr; на него
# никто не ссылается, а tokenizer.h включает
# models/test_model.h, которого нет в репозитории.
file(GLOB_RECURSE HEADER_FILES "*.h" "*.hpp")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_SOURCE_DIR}/bin)
add_executable(Xenith ${SOURCES} ${HEADER_FILES})
# Пути include:
# ${CMAKE_SOURCE_DIR} — для "xenith/core/..." из main.cpp
# ${CMAKE_SOURCE_DIR}/xenith — для "libs/json-3.12.0/..." и "core/..."
# xenith/core, xenith/backend — для "tensor.h" из backend.h и наоборот
target_include_directories(Xenith PRIVATE
${CMAKE_SOURCE_DIR}
${CMAKE_SOURCE_DIR}/xenith
@@ -117,19 +99,28 @@ target_compile_definitions(Xenith PRIVATE
find_package(Threads REQUIRED)
target_link_libraries(Xenith PRIVATE Threads::Threads)
# cpp-httplib в режиме сервера: на Windows нужны сокет-библиотеки
if(WIN32)
target_link_libraries(Xenith PRIVATE ws2_32 crypt32)
endif()
# ---------------------------------------------------------------------------
# Vulkan
# Vulkan (Портативный поиск + Fallback на систему)
# ---------------------------------------------------------------------------
if(XENITH_VULKAN)
# 1. Сначала ищем локальный SDK в папке vulkan-sdk/
if(EXISTS "${CMAKE_SOURCE_DIR}/vulkan-sdk")
set(Vulkan_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/vulkan-sdk/Include" CACHE PATH "" FORCE)
set(Vulkan_LIBRARY "${CMAKE_SOURCE_DIR}/vulkan-sdk/Lib/vulkan-1.lib" CACHE FILEPATH "" FORCE)
message(STATUS "Используется ЛОКАЛЬНЫЙ Vulkan SDK из ./vulkan-sdk/")
endif()
# 2. Стандартный поиск (подхватит кэш или системный SDK)
find_package(Vulkan)
if(NOT Vulkan_FOUND)
message(FATAL_ERROR
"XENITH_VULKAN=ON, но Vulkan SDK не найден.\n"
" Положи SDK в папку ./vulkan-sdk/ (Include/ и Lib/) для портативности\n"
" Ubuntu/Debian : sudo apt install libvulkan-dev vulkan-tools glslc\n"
" или Vulkan SDK: https://vulkan.lunarg.com\n"
" или собери без Vulkan: cmake -B build -DXENITH_VULKAN=OFF")
@@ -139,8 +130,8 @@ if(XENITH_VULKAN)
if(NOT EXISTS ${SHADERS_BIN})
message(FATAL_ERROR
"Не найден ${SHADERS_BIN}.\n"
" Сгенерируй его: python3 tools/gen_shaders.py && python3 tools/build_shaders.py\n"
" (нужен glslc из Vulkan SDK)")
" Сгенерируй его: python tools/gen_shaders.py && python tools/build_shaders.py\n"
" (нужен glslangValidator.exe в папке tools/)")
endif()
target_sources(Xenith PRIVATE xenith/backend/vk_backend.cpp)
@@ -164,8 +155,8 @@ endif()
# ---------------------------------------------------------------------------
add_custom_target(shaders
COMMAND ${CMAKE_COMMAND} -E echo "Генерация и компиляция шейдеров..."
COMMAND python3 ${CMAKE_SOURCE_DIR}/tools/gen_shaders.py
COMMAND python3 ${CMAKE_SOURCE_DIR}/tools/build_shaders.py
COMMAND python ${CMAKE_SOURCE_DIR}/tools/gen_shaders.py
COMMAND python ${CMAKE_SOURCE_DIR}/tools/build_shaders.py
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
COMMENT "xenith/backend/shaders -> shaders_bin.h")
+295
View File
@@ -0,0 +1,295 @@
# _xenith.ps1 - Auto-completion for Xenith in PowerShell
$subcommands = @(
"new", "train", "fine-tune", "gen", "chat",
"ollama", "info", "gradcheck", "bench",
"update", "devices", "doctor", "config"
)
$commandDescriptions = @{
"new" = "создать новую модель из текстового корпуса"
"train" = "обучить модель на сплошном тексте (pre-train)"
"fine-tune" = "дообучить модель на JSON-датасете диалогов"
"gen" = "сгенерировать продолжение текста"
"chat" = "интерактивный режим диалога"
"ollama" = "запустить HTTP-сервер с Ollama API"
"info" = "показать конфигурацию и словарь модели"
"gradcheck" = "численная проверка градиентов"
"bench" = "замер скорости вычислений"
"update" = "проверить и установить обновления"
"devices" = "список доступных Vulkan устройств"
"doctor" = "полная диагностика системы"
"config" = "управление настройками config.yaml"
}
function Get-XenithCompletion {
param(
$wordToComplete,
$commandAst,
$cursorPosition
)
$commandElements = $commandAst.CommandElements
$subcommand = $null
# Ищем подкоманду в аргументах
for ($i = 1; $i -lt $commandElements.Count; $i++) {
$val = $commandElements[$i].Value
if ($subcommands -contains $val) {
$subcommand = $val
break
}
}
# Если подкоманда еще не выбрана, предлагаем список команд
if (-not $subcommand) {
foreach ($cmd in $subcommands) {
if ($cmd -like "$wordToComplete*") {
[System.Management.Automation.CompletionResult]::new(
$cmd,
$cmd,
'ParameterValue',
$commandDescriptions[$cmd]
)
}
}
return
}
# Вспомогательная функция для создания результата параметра
function New-ParamResult {
param($Name, $Desc, $Type = 'ParameterName')
[System.Management.Automation.CompletionResult]::new(
"--$Name",
"--$Name",
$Type,
$Desc
)
}
# Вспомогательная функция для файловых результатов
function New-FileResult {
param($Path)
[System.Management.Automation.CompletionResult]::new(
$Path,
$Path,
'ProviderItem',
"File: $Path"
)
}
switch ($subcommand) {
"new" {
$params = @(
@{Name="corpus"; Desc="текст для построения словаря"},
@{Name="out"; Desc="путь к файлу модели (*.xnh)"},
@{Name="vocab"; Desc="размер словаря (по умолчанию 512)"},
@{Name="embd"; Desc="ширина эмбеддинга (по умолчанию 128)"},
@{Name="layers"; Desc="число слоев трансформера (по умолчанию 4)"},
@{Name="heads"; Desc="число голов внимания (должно делить embd)"},
@{Name="ctx"; Desc="максимальный контекст (по умолчанию 128)"},
@{Name="ffn"; Desc="ширина FFN слоя (0 = 4*embd)"},
@{Name="rope"; Desc="база частот RoPE (по умолчанию 10000)"},
@{Name="seed"; Desc="зерно инициализации весов"},
@{Name="untied"; Desc="использовать отдельную матрицу выхода"; Type="Switch"},
@{Name="view-vocab"; Desc="вывести содержимое словаря в stdout"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"train" {
$params = @(
@{Name="corpus"; Desc="обучающий текст"},
@{Name="out"; Desc="куда сохранить обученную модель (*.xnh)"},
@{Name="steps"; Desc="количество шагов обучения"},
@{Name="batch"; Desc="размер батча"},
@{Name="block"; Desc="длина окна контекста"},
@{Name="lr"; Desc="скорость обучения (learning rate)"},
@{Name="wd"; Desc="weight decay (регуляризация)"},
@{Name="clip"; Desc="клиппинг нормы градиента"},
@{Name="warmup"; Desc="количество шагов прогрева LR"},
@{Name="seed"; Desc="зерно генератора случайных чисел"},
@{Name="log-every"; Desc="частота вывода логов (шагов)"},
@{Name="ckpt-every"; Desc="сохранять чекпоинт каждые N шагов"},
@{Name="val-every"; Desc="валидация каждые N шагов"},
@{Name="val-tokens"; Desc="размер валидационной выборки"},
@{Name="threads"; Desc="количество потоков CPU (0 = все ядра)"},
@{Name="resume"; Desc="продолжить обучение с сохраненного состояния"; Type="Switch"},
@{Name="vulkan"; Desc="использовать GPU через Vulkan"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"fine-tune" {
$params = @(
@{Name="data"; Desc="JSON-датасет диалогов (*.json)"},
@{Name="ds-conf"; Desc="конфигурация парсера датасета (*.json)"},
@{Name="out"; Desc="куда сохранить результат (*.xnh)"},
@{Name="steps"; Desc="количество шагов дообучения"},
@{Name="batch"; Desc="размер батча"},
@{Name="block"; Desc="длина окна (должна вмещать диалог)"},
@{Name="lr"; Desc="скорость обучения (обычно 3e-5)"},
@{Name="wd"; Desc="weight decay (обычно 0.0)"},
@{Name="warmup"; Desc="шаги прогрева"},
@{Name="clip"; Desc="клиппинг градиента"},
@{Name="mask"; Desc="учить только ответы ассистента"; Type="Switch"},
@{Name="no-mask"; Desc="учить все токены подряд"; Type="Switch"},
@{Name="user-loss"; Desc="учить также реплики пользователя"; Type="Switch"},
@{Name="resume"; Desc="продолжить с последнего чекпоинта"; Type="Switch"},
@{Name="log-every"; Desc="частота вывода логов"},
@{Name="threads"; Desc="количество потоков CPU"},
@{Name="vulkan"; Desc="использовать GPU через Vulkan"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"gen" {
$params = @(
@{Name="prompt"; Desc="стартовый текст"},
@{Name="n"; Desc="количество генерируемых токенов"},
@{Name="temp"; Desc="температура выборки (0 = жадный выбор)"},
@{Name="top-k"; Desc="top-k sampling"},
@{Name="top-p"; Desc="top-p nucleus sampling"},
@{Name="repeat-penalty"; Desc="штраф за повторение токенов"},
@{Name="seed"; Desc="зерно генератора"},
@{Name="no-stream"; Desc="вывести результат целиком после генерации"; Type="Switch"},
@{Name="batch"; Desc="несколько промптов через точку с запятой"},
@{Name="show-tokens"; Desc="показывать ID токенов при генерации"; Type="Switch"},
@{Name="threads"; Desc="количество потоков CPU"},
@{Name="vulkan"; Desc="использовать GPU"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"chat" {
$params = @(
@{Name="system"; Desc="системный промпт"},
@{Name="no-system"; Desc="отключить системный промпт"; Type="Switch"},
@{Name="n"; Desc="максимум токенов в ответе"},
@{Name="temp"; Desc="температура"},
@{Name="top-k"; Desc="top-k"},
@{Name="top-p"; Desc="top-p"},
@{Name="repeat-penalty"; Desc="штраф за повторы"},
@{Name="seed"; Desc="зерно"},
@{Name="no-stream"; Desc="не печатать посимвольно"; Type="Switch"},
@{Name="show-tokens"; Desc="показывать ID токенов"; Type="Switch"},
@{Name="threads"; Desc="количество потоков"},
@{Name="vulkan"; Desc="использовать GPU"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"ollama" {
$params = @(
@{Name="port"; Desc="порт сервера (по умолчанию 11434)"},
@{Name="host"; Desc="адрес хоста (0.0.0.0 для всех)"},
@{Name="conf"; Desc="путь к JSON конфигу"},
@{Name="model"; Desc="модель по умолчанию"},
@{Name="no-scan"; Desc="не сканировать папку models автоматически"; Type="Switch"},
@{Name="verbose"; Desc="подробный лог запросов"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"info" {
$params = @(
@{Name="vulkan"; Desc="использовать GPU для проверки/бенча"; Type="Switch"},
@{Name="verbose"; Desc="подробный вывод"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"gradcheck" {
$params = @(
@{Name="vulkan"; Desc="использовать GPU"; Type="Switch"},
@{Name="verbose"; Desc="подробный вывод"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"bench" {
$params = @(
@{Name="vulkan"; Desc="использовать GPU"; Type="Switch"},
@{Name="verbose"; Desc="подробный вывод"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"update" {
$params = @(
@{Name="check"; Desc="только проверить наличие обновлений"; Type="Switch"},
@{Name="dry-run"; Desc="показать план действий без изменений"; Type="Switch"},
@{Name="yes"; Desc="подтвердить обновление автоматически"; Type="Switch"},
@{Name="force"; Desc="принудительное обновление"; Type="Switch"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
"config" {
$params = @(
@{Name="init"; Desc="создать дефолтный config.yaml"; Type="Switch"},
@{Name="all"; Desc="показать все настройки"; Type="Switch"},
@{Name="path"; Desc="показать путь к текущему конфигу"; Type="Switch"},
@{Name="get"; Desc="получить значение параметра"}
)
foreach ($p in $params) {
if ("--$($p.Name)" -like "$wordToComplete*") {
New-ParamResult -Name $p.Name -Desc $p.Desc -Type $p.Type
}
}
}
default {
# Для commands без аргументов (devices, doctor, version) ничего не делаем
}
}
}
# Регистрируем комплитер для команды Xenith
Register-ArgumentCompleter -CommandName Xenith -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
Get-XenithCompletion -wordToComplete $wordToComplete -commandAst $commandAst -cursorPosition $cursorPosition
}
# Если у тебя есть алиас ./bin/Xenith, можно зарегистрировать и для него,
# но в PS лучше использовать функцию-обертку, которую мы создали в activate.ps1
+69
View File
@@ -0,0 +1,69 @@
# Xenith PowerShell Activation Script
# Минималистичная версия: только PATH и алиасы для инструментов
# 1. Устанавливаем переменную для промпта
$env:VIRTUAL_ENV_PROMPT = "Xenith"
# 2. Добавляем локальные инструменты в начало PATH текущей сессии
# Приоритет отдается ./tools/, затем ./tools/cmake/bin/
$projectRoot = $PSScriptRoot
$toolsPath = Join-Path $projectRoot "tools"
$cmakeBinPath = Join-Path $toolsPath "cmake" "bin"
if (Test-Path $cmakeBinPath) {
$env:Path = "$cmakeBinPath;$toolsPath;$env:Path"
} elseif (Test-Path $toolsPath) {
$env:Path = "$toolsPath;$env:Path"
}
# 3. Алиасы для быстрых команд проекта
function global:Xenith { & "./bin/Xenith.exe" @args }
function global:Build_Shaders { python ./tools/build_shaders.py @args }
function global:Gen_Shaders { python ./tools/gen_shaders.py @args }
# 4. Настройка промпта
if (-not (Test-Path variable:_OLD_VIRTUAL_PS1)) {
$global:_old_fish_prompt = $function:prompt
$global:_OLD_VIRTUAL_PS1 = $true
function global:prompt {
Write-Host "(Xenith) " -NoNewline -ForegroundColor Red
& $global:_old_fish_prompt
}
}
# 5. Функция деактивации (полный откат состояния)
function global:deactivate {
Remove-Item function:Xenith, function:Build_Shaders, function:Gen_Shaders -ErrorAction SilentlyContinue
if (Test-Path variable:_old_fish_prompt) {
$function:prompt = $global:_old_fish_prompt
Remove-Item variable:_old_fish_prompt -ErrorAction SilentlyContinue
}
Remove-Item env:VIRTUAL_ENV_PROMPT, variable:_OLD_VIRTUAL_PS1 -ErrorAction SilentlyContinue
if (Test-Path function:builtin_deactivate) { & builtin_deactivate }
Remove-Item function:deactivate -ErrorAction SilentlyContinue
Write-Host "Xenith deactivated" -ForegroundColor Yellow
}
# 6. Автодополнение для команды Xenith
if (Test-Path "./_xenith.ps1") {
. "./_xenith.ps1"
} else {
Register-ArgumentCompleter -CommandName Xenith -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$commands = @("new", "train", "fine-tune", "gen", "chat",
"ollama", "info", "gradcheck", "bench",
"update", "devices", "doctor", "config")
foreach ($cmd in $commands) {
if ($cmd -like "$wordToComplete*") {
[System.Management.Automation.CompletionResult]::new($cmd, $cmd, 'ParameterValue', $cmd)
}
}
}
}
Write-Host "Xenith environment activated" -ForegroundColor Green
+66 -31
View File
@@ -10,37 +10,83 @@ SHADER_DIR = os.path.join(ROOT, "xenith", "backend", "shaders")
OUT_HEADER = os.path.join(ROOT, "xenith", "backend", "shaders_bin.h")
def find_compiler():
for name in ("glslc", "glslangValidator"):
p = shutil.which(name)
if p:
return name, p
script_dir = os.path.dirname(os.path.abspath(__file__))
local_tool = os.path.join(script_dir, "glslangValidator.exe")
if os.path.exists(local_tool):
return "glslangValidator", local_tool
p = shutil.which("glslangValidator")
if p:
return "glslangValidator", p
p = shutil.which("glslc")
if p:
return "glslc", p
for cand in (os.environ.get("VULKAN_SDK"), "/usr/local/vulkan", os.path.expanduser("~/VulkanSDK")):
if not cand:
continue
for sub in ("bin/glslc", "bin/glslangValidator"):
p = os.path.join(cand, sub)
if os.path.exists(p):
return os.path.basename(p), p
full_path = os.path.join(cand, sub)
if os.path.exists(full_path):
return os.path.basename(full_path), full_path
return None, None
def compile_one(compiler, path, compiler_path, spv_out):
if compiler == "glslc":
cmd = [compiler_path,
"-I", SHADER_DIR, # чтобы #include "common.glsl" работал
"-O", # оптимизация SPIR-V
"-I", SHADER_DIR,
"-O",
"--target-env=vulkan1.1",
"-o", spv_out, path]
r = subprocess.run(cmd, capture_output=True, text=True)
return r.returncode, (r.stdout or "") + (r.stderr or "")
else:
# glslangValidator не умеет -I напрямую в старых версиях: используем -I<dir>
cmd = [compiler_path,
"-I" + SHADER_DIR,
"-V", # Vulkan SPIR-V
"-o", spv_out, path]
r = subprocess.run(cmd, capture_output=True, text=True)
return r.returncode, (r.stdout or "") + (r.stderr or "")
import tempfile
with open(path, 'r', encoding='utf-8') as f:
lines = f.readlines()
# Ищем строку с #version
version_line_idx = -1
for i, line in enumerate(lines):
stripped = line.strip()
if stripped.startswith('#version'):
version_line_idx = i
break
modified_lines = list(lines)
# Если нашли #version, вставляем extension СРАЗУ ПОСЛЕ неё
if version_line_idx >= 0:
ext_directive = '#extension GL_GOOGLE_include_directive : enable\n'
# Проверяем, нет ли уже такой директивы
has_ext = any('GL_GOOGLE_include_directive' in l for l in lines)
if not has_ext:
modified_lines.insert(version_line_idx + 1, ext_directive)
else:
# Если #version нет (не должно быть для Vulkan), добавляем в начало
# Но лучше просто добавить extension в начало, если version отсутствует
ext_directive = '#extension GL_GOOGLE_include_directive : enable\n'
has_ext = any('GL_GOOGLE_include_directive' in l for l in lines)
if not has_ext:
modified_lines.insert(0, ext_directive)
# Пишем во временный файл
with tempfile.NamedTemporaryFile(mode='w', suffix='.comp',
delete=False, encoding='utf-8') as tmp:
tmp.writelines(modified_lines)
tmp_path = tmp.name
try:
cmd = [compiler_path,
f"-I{SHADER_DIR}",
"-V",
"--target-env", "vulkan1.1",
"-o", spv_out,
tmp_path]
r = subprocess.run(cmd, capture_output=True, text=True)
return r.returncode, (r.stdout or "") + (r.stderr or "")
finally:
os.unlink(tmp_path)
def main():
compiler, cpath = find_compiler()
@@ -49,19 +95,16 @@ def main():
print("Установи Vulkan SDK (https://vulkan.lunarg.com) или пакет shaderc/glslang,", file=sys.stderr)
print("либо собери проект без Vulkan: cmake -DXENITH_VULKAN=OFF", file=sys.stderr)
return 1
print(f"компилятор: {compiler} ({cpath})")
print(f"каталог : {SHADER_DIR}")
sources = sorted(f for f in os.listdir(SHADER_DIR) if f.endswith(".comp"))
if not sources:
print("нет ни одного .comp — сначала запусти tools/gen_shaders.py", file=sys.stderr)
return 1
blobs = []
failed = 0
for src in sources:
name = src[:-5] # без .comp
name = src[:-5]
spv = os.path.join(SHADER_DIR, name + ".spv")
rc, log = compile_one(compiler, os.path.join(SHADER_DIR, src), cpath, spv)
if rc != 0 or not os.path.exists(spv):
@@ -74,17 +117,13 @@ def main():
print(f" ✗ {src}: файл не похож на SPIR-V (магия {data[:4].hex()})")
failed += 1
continue
# SPIR-V — массив uint32; проверяем кратность 4
if len(data) % 4:
data = data[: len(data) - (len(data) % 4)]
blobs.append((name, data))
print(f"[OK] {src:22} > {len(data):7d} байт ({len(data)//4} слов)")
if failed:
print(f"\n{failed} шейдеров не собрались — заголовок НЕ перезаписан", file=sys.stderr)
return 1
# --- генерация заголовка ---
lines = []
lines.append("// shaders_bin.h — SPIR-V шейдеры, упакованные в бинарник.")
lines.append("// СГЕНЕРИРОВАН АВТОМАТИЧЕСКИ: tools/build_shaders.py — руками не править.")
@@ -98,7 +137,6 @@ def main():
words = len(data) // 4
lines.append(f"// {name}.comp — {words} слов")
lines.append(f"static const uint32_t xenith_spv_{name}[{words}] = {{")
# по 12 uint32 в строке для читаемости
row = []
for i in range(0, len(data), 4):
w = int.from_bytes(data[i:i+4], "little")
@@ -115,13 +153,10 @@ def main():
with open(OUT_HEADER, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
total = sum(len(d) for _, d in blobs)
print(f"\nзаписано {OUT_HEADER}")
print(f" шейдеров: {len(blobs)}, суммарно {total} байт SPIR-V "
f"({total/1024:.1f} КиБ, в заголовке ~{os.path.getsize(OUT_HEADER)/1024:.0f} КиБ)")
return 0
if __name__ == "__main__":
sys.exit(main())
sys.exit(main())
Binary file not shown.
+102
View File
@@ -0,0 +1,102 @@
Contributors
************
The following individuals and institutions are among the contributors:
* `Aaron C. Meadows <mailto:cmake@shadowguarddev.com>`__
* `Adriaan de Groot <mailto:groot@kde.org>`__
* `Aleksey Avdeev <mailto:solo@altlinux.ru>`__
* `Alexander Neundorf <mailto:neundorf@kde.org>`__
* `Alexander Smorkalov <mailto:alexander.smorkalov@itseez.com>`__
* `Alexey Sokolov <mailto:sokolov@google.com>`__
* `Alex Merry <mailto:alex.merry@kde.org>`__
* `Alex Turbov <mailto:i.zaufi@gmail.com>`__
* `Andreas Pakulat <mailto:apaku@gmx.de>`__
* `Andreas Schneider <mailto:asn@cryptomilk.org>`__
* `André Rigland Brodtkorb <mailto:Andre.Brodtkorb@ifi.uio.no>`__
* Axel Huebl, Helmholtz-Zentrum Dresden - Rossendorf
* Benjamin Eikel
* `Bjoern Ricks <mailto:bjoern.ricks@gmail.com>`__
* `Brad Hards <mailto:bradh@kde.org>`__
* Christopher Harvey
* `Christoph Grüninger <mailto:foss@grueninger.de>`__
* `Clement Creusot <mailto:creusot@cs.york.ac.uk>`__
* `Daniel Blezek <mailto:blezek@gmail.com>`__
* `Daniel Pfeifer <mailto:daniel@pfeifer-mail.de>`__
* `Dawid Wróbel <mailto:me@dawidwrobel.com>`__
* `Enrico Scholz <mailto:enrico.scholz@informatik.tu-chemnitz.de>`__
* `Eran Ifrah <mailto:eran.ifrah@gmail.com>`__
* Esben Mose Hansen, Ange Optimization ApS
* `Geoffrey Viola <mailto:geoffrey.viola@asirobots.com>`__
* `Georg Brandl <mailto:georg@python.org>`__
* `Google Inc <https://www.google.com/>`__
* Gregor Jasny
* `Helio Chissini de Castro <mailto:helio@kde.org>`__
* `Ilya Lavrenov <mailto:ilya.lavrenov@itseez.com>`__
* `Insight Software Consortium <https://insightsoftwareconsortium.org/>`__
* `Intel Corporation <https://www.intel.com/>`__
* Jan Woetzel
* `Jordan Williams <mailto:jordan@jwillikers.com>`__
* Julien Schueller
* `Kelly Thompson <mailto:kgt@lanl.gov>`__
* `Konstantin Podsvirov <mailto:konstantin@podsvirov.su>`__
* `Laurent Montel <mailto:montel@kde.org>`__
* `Mario Bensi <mailto:mbensi@ipsquad.net>`__
* `Martin Gräßlin <mailto:mgraesslin@kde.org>`__
* `Mathieu Malaterre <mailto:mathieu.malaterre@gmail.com>`__
* Matthaeus G. Chajdas
* `Matthias Kretz <mailto:kretz@kde.org>`__
* `Matthias Maennich <mailto:matthias@maennich.net>`__
* `Michael Hirsch, Ph.D. <https://www.scivision.dev/>`__
* Michael Stürmer
* Miguel A. Figueroa-Villanueva
* `Mike Durso <mailto:rbprogrammer@gmail.com>`__
* Mike Jackson
* `Mike McQuaid <mailto:mike@mikemcquaid.com>`__
* `Nicolas Bock <mailto:nicolasbock@gmail.com>`__
* `Nicolas Despres <mailto:nicolas.despres@gmail.com>`__
* `Nikita Krupen'ko <mailto:krnekit@gmail.com>`__
* `NVIDIA Corporation <https://www.nvidia.com/>`__
* `OpenGamma Ltd. <https://opengamma.com/>`__
* `Patrick Stotko <mailto:stotko@cs.uni-bonn.de>`__
* `Per Øyvind Karlsen <mailto:peroyvind@mandriva.org>`__
* `Peter Collingbourne <mailto:peter@pcc.me.uk>`__
* `Petr Gotthard <mailto:gotthard@honeywell.com>`__
* `Philip Lowman <mailto:philip@yhbt.com>`__
* `Philippe Proulx <mailto:pproulx@efficios.com>`__
* `Qualcomm Technologies, Inc. <https://www.qualcomm.com>`__
* Raffi Enficiaud, Max Planck Society
* Raumfeld
* `Roger Leigh <mailto:rleigh@codelibre.net>`__
* `Rolf Eike Beer <mailto:eike@sf-mail.de>`__
* `Roman Donchenko <mailto:roman.donchenko@itseez.com>`__
* `Roman Kharitonov <mailto:roman.kharitonov@itseez.com>`__
* Ruslan Baratov
* `Sebastian Holtermann <mailto:sebholt@xwmw.org>`__
* `Stephen Kelly <mailto:steveire@gmail.com>`__
* `Sylvain Joubert <mailto:joubert.sy@gmail.com>`__
* `The Qt Company Ltd. <https://www.qt.io/>`__
* `Thomas Sondergaard <mailto:ts@medical-insight.com>`__
* `Tobias Hunger <mailto:tobias.hunger@qt.io>`__
* `Todd Gamblin <mailto:tgamblin@llnl.gov>`__
* Tristan Carel
* `University of Dundee <https://www.dundee.ac.uk/>`__
* Vadim Zhukov
* `Will Dicharry <mailto:wdicharry@stellarscience.com>`__
See version control history for details of individual contributions.
Copyright
=========
The accompanying `LICENSE.rst`_ notice applies to distributions of CMake
in source and binary form. We do not require any formal copyright
assignment or contributor license agreement. Any contributions
intentionally sent upstream are presumed to be offered under terms
of the OSI-approved BSD 3-clause License.
Third-party software packages supplied with CMake under compatible
licenses provide their own copyright notices documented in corresponding
subdirectories or source files.
.. _`LICENSE.rst`: LICENSE.rst
+28
View File
@@ -0,0 +1,28 @@
Copyright 2000-2026 Kitware, Inc. and `Contributors <CONTRIBUTORS.rst>`_
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Kitware, Inc. nor the names of Contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+7
View File
@@ -0,0 +1,7 @@
<html>
<head>
<meta http-equiv="Refresh" content="0; url=https://cmake.org/" />
</head>
<body>
</body>
</html>
+5
View File
@@ -0,0 +1,5 @@
'cppdap' is a C++11 library implementation of the Debug Adapter Protocol.
Version as of 2023-01-06
Copyright Google LLC
This product includes software developed at Google.
+22
View File
@@ -0,0 +1,22 @@
COPYRIGHT AND PERMISSION NOTICE
Copyright (c) 1996 - 2026, Daniel Stenberg, <daniel@haxx.se>, and many
contributors, see the THANKS file.
All rights reserved.
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of a copyright holder shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization of the copyright holder.
@@ -0,0 +1,65 @@
The libarchive distribution as a whole is Copyright by Tim Kientzle
and is subject to the copyright notice reproduced at the bottom of
this file.
Each individual file in this distribution should have a clear
copyright/licensing statement at the beginning of the file. If any do
not, please let me know and I will rectify it. The following is
intended to summarize the copyright status of the individual files;
the actual statements in the files are controlling.
* Except as listed below, all C sources (including .c and .h files)
and documentation files are subject to the copyright notice reproduced
at the bottom of this file.
* The following source files are also subject in whole or in part to
a 3-clause UC Regents copyright; please read the individual source
files for details:
libarchive/archive_read_support_filter_compress.c
libarchive/archive_write_add_filter_compress.c
libarchive/mtree.5
* The following source files are in the public domain:
libarchive/archive_parse_date.c
* The following source files are triple-licensed with the ability to choose
from CC0 1.0 Universal, OpenSSL or Apache 2.0 licenses:
libarchive/archive_blake2.h
libarchive/archive_blake2_impl.h
libarchive/archive_blake2s_ref.c
libarchive/archive_blake2sp_ref.c
* The build files---including Makefiles, configure scripts,
and auxiliary scripts used as part of the compile process---have
widely varying licensing terms. Please check individual files before
distributing them to see if those restrictions apply to you.
I intend for all new source code to use the license below and hope over
time to replace code with other licenses with new implementations that
do use the license below. The varying licensing of the build scripts
seems to be an unavoidable mess.
Copyright (c) 2003-2018 <author(s)>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer
in this position and unchanged.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+83
View File
@@ -0,0 +1,83 @@
XZ Utils Licensing
==================
Different licenses apply to different files in this package. Here
is a summary of which licenses apply to which parts of this package:
- liblzma is under the BSD Zero Clause License (0BSD).
- The command line tools xz, xzdec, lzmadec, and lzmainfo are
under 0BSD except that, on systems that don't have a usable
getopt_long, GNU getopt_long is compiled and linked in from the
'lib' directory. The getopt_long code is under GNU LGPLv2.1+.
- The scripts to grep, diff, and view compressed files have been
adapted from GNU gzip. These scripts (xzgrep, xzdiff, xzless,
and xzmore) are under GNU GPLv2+. The man pages of the scripts
are under 0BSD; they aren't based on the man pages of GNU gzip.
- Most of the XZ Utils specific documentation that is in
plain text files (like README, INSTALL, PACKAGERS, NEWS,
and ChangeLog) are under 0BSD unless stated otherwise in
the file itself. The files xz-file-format.txt and
lzma-file-format.xt are in the public domain but may
be distributed under the terms of 0BSD too.
- Translated messages and man pages are under 0BSD except that
some old translations are in the public domain.
- Test files and test code in the 'tests' directory, and
debugging utilities in the 'debug' directory are under
the BSD Zero Clause License (0BSD).
- The GNU Autotools based build system contains files that are
under GNU GPLv2+, GNU GPLv3+, and a few permissive licenses.
These files don't affect the licensing of the binaries being
built.
- The 'extra' directory contains files that are under various
free software licenses. These aren't built or installed as
part of XZ Utils.
For the files under the BSD Zero Clause License (0BSD), if
a copyright notice is needed, the following is sufficient:
Copyright (C) The XZ Utils authors and contributors
If you copy significant amounts of 0BSD-licensed code from XZ Utils
into your project, acknowledging this somewhere in your software is
polite (especially if it is proprietary, non-free software), but
it is not legally required by the license terms. Here is an example
of a good notice to put into "about box" or into documentation:
This software includes code from XZ Utils <https://tukaani.org/xz/>.
The following license texts are included in the following files:
- COPYING.0BSD: BSD Zero Clause License
- COPYING.LGPLv2.1: GNU Lesser General Public License version 2.1
- COPYING.GPLv2: GNU General Public License version 2
- COPYING.GPLv3: GNU General Public License version 3
A note about old XZ Utils releases:
XZ Utils releases 5.4.6 and older and 5.5.1alpha have a
significant amount of code put into the public domain and
that obviously remains so. The switch from public domain to
0BSD for newer releases was made in Febrary 2024 because
public domain has (real or perceived) legal ambiguities in
some jurisdictions.
There is very little *practical* difference between public
domain and 0BSD. The main difference likely is that one
shouldn't claim that 0BSD-licensed code is in the public
domain; 0BSD-licensed code is copyrighted but available under
an extremely permissive license. Neither 0BSD nor public domain
require retaining or reproducing author, copyright holder, or
license notices when distributing the software. (Compare to,
for example, BSD 2-Clause "Simplified" License which does have
such requirements.)
If you have questions, don't hesitate to ask for more information.
The contact information is in the README file.
+15
View File
@@ -0,0 +1,15 @@
BSD Zero Clause License
Copyright (c) 2005, Aleksey Kravchenko <rhash.admin@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
+19
View File
@@ -0,0 +1,19 @@
Copyright (c) 2015-present libuv project contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
+23
View File
@@ -0,0 +1,23 @@
The MIT License
Copyright (c) 2012, 2014, 2015, 2016 Tatsuhiro Tsujikawa
Copyright (c) 2012, 2014, 2015, 2016 nghttp2 contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+38
View File
@@ -0,0 +1,38 @@
KWSys - Kitware System Library
Copyright 2000-2016 Kitware, Inc. and Contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Kitware, Inc. nor the names of Contributors
may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
------------------------------------------------------------------------------
The following individuals and institutions are among the Contributors:
* Insight Software Consortium <insightsoftwareconsortium.org>
See version control history for details of individual contributions.
@@ -0,0 +1,23 @@
'zlib' general purpose compression library
version 1.3.1, January 22nd, 2024
Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
Jean-loup Gailly Mark Adler
jloup@gzip.org madler@alumni.caltech.edu
+30
View File
@@ -0,0 +1,30 @@
BSD License
For Zstandard software
Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name Facebook, nor Meta, nor the names of its contributors may
be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,83 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Schema for the CMake cache object kind",
"type": "object",
"required": [
"kind",
"version",
"entries"
],
"properties": {
"kind": {
"type": "string",
"const": "cache"
},
"version": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 2
},
"minor": {
"type": "integer",
"const": 0
}
},
"additionalProperties": false
},
"entries": {
"type": "array",
"description": "Array of CMake cache entries",
"items": {
"type": "object",
"required": [
"name",
"value",
"type",
"properties"
],
"properties": {
"name": {
"type": "string",
"description": "Name of the cache entry"
},
"value": {
"type": "string",
"description": "Value of the cache entry"
},
"type": {
"type": "string",
"description": "Type of the cache entry used by CMake GUI to choose a widget for editing"
},
"properties": {
"type": "array",
"description": "Associated properties for the cache entry",
"items": {
"type": "object",
"required": [
"name",
"value"
],
"properties": {
"name": {
"type": "string"
},
"value": {
"type": "string"
}
},
"additionalProperties": false
}
}
},
"additionalProperties": false
}
}
},
"additionalProperties": false
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,84 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Schema for CMake file API query.json files",
"type": "object",
"required": [
"requests"
],
"properties": {
"requests": {
"type": "array",
"items": {
"type": "object",
"required": [
"kind",
"version"
],
"properties": {
"kind": {
"type": "string",
"description": "Specifies one of the Object Kinds to be included in the reply"
},
"version": {
"description": "Version(s) of the object kind that the client understands",
"oneOf": [
{
"$ref": "#/definitions/versionMajorOnly"
},
{
"$ref": "#/definitions/versionObject"
},
{
"type": "array",
"items": {
"oneOf": [
{
"$ref": "#/definitions/versionMajorOnly"
},
{
"$ref": "#/definitions/versionObject"
}
]
}
}
]
},
"client": {
"description": "Optional member reserved for use by the client. This value is preserved in the reply."
}
}
}
},
"client": {
"description": "Optional member reserved for use by the client. This value is preserved in the reply."
}
},
"$comment": "Other top level properties are reserved for future use. If present, they are ignored for forward compatibility.",
"additionalProperties": true,
"definitions": {
"versionMajorOnly": {
"type": "integer",
"description": "A non-negative major version number",
"minimum": 0
},
"versionObject": {
"type": "object",
"required": [
"major"
],
"properties": {
"major": {
"type": "integer",
"description": "The major version number",
"minimum": 0
},
"minor": {
"type": "integer",
"description": "The minor version number",
"minimum": 0
}
},
"additionalProperties": false
}
}
}
@@ -0,0 +1,241 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Schema for the CMake toolchains object kind",
"type": "object",
"required": [
"kind",
"version",
"toolchains"
],
"oneOf": [
{
"$ref": "#/definitions/toolchainsObjV1_0"
},
{
"$ref": "#/definitions/toolchainsObjV1_1"
}
],
"definitions": {
"kind": {
"type": "string",
"const": "toolchains",
"description": "Specifies the object kind"
},
"versionV1_0": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"const": 0
}
},
"additionalProperties": false
},
"versionV1_1": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"const": 1
}
},
"additionalProperties": false
},
"language": {
"type": "string",
"description": "Toolchain language identifier (e.g. C, CXX)"
},
"sourceFileExtensions": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of source file extensions (without leading dot) supported by this toolchain"
},
"compilerPath": {
"type": "string",
"description": "Path to the compiler executable. This is present when the CMAKE_<LANG>_COMPILER variable is defined."
},
"compilerCommandFragment": {
"type": "string",
"description": "Mandatory arguments to the compiler, as a command line fragment. This is present when the CMAKE_<LANG>_COMPILER variable is a list containing multiple elements or the CC or similar environment variable contains command line arguments."
},
"compilerId": {
"type": "string",
"description": "Compiler identifier (e.g. GNU, MSVC). This is present when the CMAKE_<LANG>_COMPILER_ID variable is defined."
},
"compilerVersion": {
"type": "string",
"description": "Version of the compiler. This is present when the CMAKE_<LANG>_COMPILER_VERSION variable is defined."
},
"compilerTarget": {
"type": "string",
"description": "Cross-compiling target of the compiler. This is present when the CMAKE_<LANG>_COMPILER_TARGET variable is defined."
},
"compilerImplicit": {
"type": "object",
"properties": {
"includeDirectories": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of implicit include directories for the compiler. This is present when the CMAKE_<LANG>_IMPLICIT_INCLUDE_DIRECTORIES variable is defined."
},
"linkDirectories": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of implicit link directories for the compiler front end. This is present when the CMAKE_<LANG>_IMPLICIT_LINK_DIRECTORIES variable is defined."
},
"linkFrameworkDirectories": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of implicit link framework directories for the compiler front end. This is present when the CMAKE_<LANG>_IMPLICIT_FRAMEWORK_DIRECTORIES variable is defined."
},
"linkLibraries": {
"type": "array",
"items": {
"type": "string"
},
"description": "List of implicit link libraries for the compiler front end. This is present when the CMAKE_<LANG>_IMPLICIT_LINK_LIBRARIES variable is defined."
}
},
"additionalProperties": false
},
"compilerV1_0": {
"type": "object",
"properties": {
"path": {
"$ref": "#/definitions/compilerPath"
},
"id": {
"$ref": "#/definitions/compilerId"
},
"version": {
"$ref": "#/definitions/compilerVersion"
},
"target": {
"$ref": "#/definitions/compilerTarget"
},
"implicit": {
"$ref": "#/definitions/compilerImplicit"
}
},
"additionalProperties": false
},
"compilerV1_1": {
"type": "object",
"properties": {
"path": {
"$ref": "#/definitions/compilerPath"
},
"commandFragment": {
"$ref": "#/definitions/compilerCommandFragment"
},
"id": {
"$ref": "#/definitions/compilerId"
},
"version": {
"$ref": "#/definitions/compilerVersion"
},
"target": {
"$ref": "#/definitions/compilerTarget"
},
"implicit": {
"$ref": "#/definitions/compilerImplicit"
}
},
"additionalProperties": false
},
"toolchainsObjV1_0": {
"type": "object",
"properties": {
"kind": {
"$ref": "#/definitions/kind"
},
"version": {
"$ref": "#/definitions/versionV1_0"
},
"toolchains": {
"type": "array",
"description": "Array of toolchain configurations per language",
"items": {
"type": "object",
"required": [
"language",
"compiler"
],
"properties": {
"language": {
"$ref": "#/definitions/language"
},
"compiler": {
"$ref": "#/definitions/compilerV1_0"
},
"sourceFileExtensions": {
"$ref": "#/definitions/sourceFileExtensions"
}
},
"additionalProperties": false
}
}
},
"additionalProperties": false
},
"toolchainsObjV1_1": {
"type": "object",
"properties": {
"kind": {
"$ref": "#/definitions/kind"
},
"version": {
"$ref": "#/definitions/versionV1_1"
},
"toolchains": {
"type": "array",
"description": "Array of toolchain configurations per language",
"items": {
"type": "object",
"required": [
"language",
"compiler"
],
"properties": {
"language": {
"$ref": "#/definitions/language"
},
"compiler": {
"$ref": "#/definitions/compilerV1_1"
},
"sourceFileExtensions": {
"$ref": "#/definitions/sourceFileExtensions"
}
},
"additionalProperties": false
}
}
},
"additionalProperties": false
}
}
}
@@ -0,0 +1,248 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": [
"cmake",
"objects",
"reply"
],
"properties": {
"cmake": {
"type": "object",
"description": "High level details about CMake itself and the CMake generator used",
"required": [
"version",
"paths",
"generator"
],
"properties": {
"version": {
"description": "Full version details of the CMake used to produce the replies",
"type": "object",
"required": [
"major",
"minor",
"patch",
"string",
"isDirty"
],
"properties": {
"major": {
"type": "integer",
"minimum": 3
},
"minor": {
"type": "integer",
"minimum": 0
},
"patch": {
"type": "integer",
"minimum": 0
},
"suffix": {
"type": "string",
"description": "A version suffix may be present when CMake is built from sources, or for release candidates. Official releases do not normally have a suffix."
},
"string": {
"type": "string",
"description": "The full version string in the format <major>.<minor>.<patch>[-<suffix>]"
},
"isDirty": {
"type": "boolean",
"description": "When this is true, it indicates CMake was built from a version-controlled source tree with local modifications"
}
},
"additionalProperties": false
},
"paths": {
"description": "Absolute paths to tools and locations within the CMake installation",
"type": "object",
"required": [
"cmake",
"ctest",
"cpack",
"root"
],
"properties": {
"cmake": {
"description": "Absolute path to the cmake executable",
"type": "string"
},
"ctest": {
"description": "Absolute path to the ctest executable",
"type": "string"
},
"cpack": {
"description": "Absolute path to the cpack executable",
"type": "string"
},
"root": {
"description": "Absolute path to the directory containing CMake resources like the Modules directory",
"type": "string"
}
},
"additionalProperties": false
},
"generator": {
"description": "Details for the CMake generator used",
"type": "object",
"required": [
"multiConfig",
"name"
],
"properties": {
"multiConfig": {
"description": "True for multi-configuration generators, false for single-configuration generators",
"type": "boolean"
},
"name": {
"type": "string"
},
"platform": {
"description": "This string will only be set if the generator supports the CMAKE_GENERATOR_PLATFORM variable, which specifies the generator platform name",
"type": "string"
}
},
"additionalProperties": false
}
}
},
"objects": {
"type": "array",
"items": {
"$ref": "#/definitions/kindJsonFile"
}
},
"reply": {
"type": "object",
"patternProperties": {
"^[^-]+-v\\d+$": {
"description": "A member of this form appears for each of the shared stateless query files that CMake recognized as a request for the specified object kind and major version",
"oneOf": [
{
"$ref": "#/definitions/kindJsonFile"
},
{
"description": "A member of this form appears if the query's object kind is not recognized or is malformed",
"$ref": "#/definitions/replyError"
}
]
},
"^client-[^/]+$": {
"description": "A member of this form appears for each client-owned directory holding client stateless query files. The value is a JSON object mirroring the content of the query/client-<client>/ directory.",
"patternProperties": {
"^[^-]+-v\\d+$": {
"description": "A member of this form appears for each of the client stateless query files that CMake recognized as a request for the specified object kind and major version",
"oneOf": [
{
"$ref": "#/definitions/kindJsonFile"
},
{
"description": "A member of this form appears if the client query's object kind is not recognized or is malformed",
"$ref": "#/definitions/replyError"
}
]
},
"^query\\.json$": {
"description": "This member appears for clients using client stateful query files",
"oneOf": [
{
"type": "object",
"properties": {
"client": {
"type": "object"
},
"requests": {},
"responses": {
"oneOf": [
{
"$ref": "#/definitions/replyError"
},
{
"type": "array",
"items": {
"oneOf": [
{
"$ref": "#/definitions/kindJsonFile"
},
{
"$ref": "#/definitions/replyError"
}
]
}
}
]
}
},
"additionalProperties": false
},
{
"description": "A member of this form appears if the query.json file failed to read or parse as a JSON object",
"$ref": "#/definitions/replyError"
}
]
}
},
"additionalProperties": {
"description": "A member of this form appears for each of the client stateless query files that CMake did not recognize.",
"$ref": "#/definitions/replyError"
}
}
},
"additionalProperties": {
"description": "A member of this form appears for each of the shared stateless query files that CMake did not recognize.",
"$ref": "#/definitions/replyError"
}
}
},
"definitions": {
"kindJsonFile": {
"type": "object",
"required": [
"kind",
"version",
"jsonFile"
],
"properties": {
"kind": {
"type": "string"
},
"version": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"minimum": 1
},
"minor": {
"type": "integer",
"minimum": 0
}
},
"additionalProperties": false
},
"jsonFile": {
"type": "string",
"description": "Specifies a path relative to the reply index file to another JSON file containing the object"
}
},
"additionalProperties": false
},
"replyError": {
"type": "object",
"required": [
"error"
],
"properties": {
"error": {
"type": "string"
}
},
"additionalProperties": false
}
}
}
@@ -0,0 +1,184 @@
{
"$schema": "http://json-schema.org/draft/2020-12/schema#",
"type": "object",
"required": [
"version",
"buildDir",
"dataDir",
"hook",
"snippets"
],
"definitions": {
"nonEmptyStringOrNull": {
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
},
"positiveIntegerOrNull": {
"anyOf": [
{
"type": "integer",
"minimum": 1
},
{
"type": "null"
}
]
}
},
"properties": {
"version": {
"description": "The data version of the index file.",
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"enum": [
0,
1
]
}
},
"additionalProperties": false
},
"buildDir": {
"type": "string",
"description": "The build directory of the CMake project.",
"minLength": 1
},
"dataDir": {
"type": "string",
"description": "The full path to the <build>/.cmake/instrumentation/v1/data/ directory.",
"minLength": 1
},
"hook": {
"type": "string",
"description": "The name of the hook responsible for generating the index file. In addition to the hooks that can be specified by one of the v1 Query Files, this value may be set to manual if indexing is performed by invoking ctest --collect-instrumentation.",
"enum": [
"postGenerate",
"preBuild",
"postBuild",
"preCMakeBuild",
"postCMakeBuild",
"postCMakeInstall",
"postCMakeWorkflow",
"postCTest",
"manual"
]
},
"snippets": {
"type": "array",
"description": "Contains a list of v1 Snippet Files. This includes all snippet files generated since the previous index file was created. The file paths are relative to dataDir.",
"items": {
"type": "string",
"minLength": 1
},
"uniqueItems": true
},
"trace": {
"type": "string",
"description": "Contains the path to the Google Trace File. This includes data from all corresponding snippets in the index file. The file path is relative to dataDir. Only included when enabled by the v1 Query Files.",
"minLength": 1
},
"staticSystemInformation": {
"type": "object",
"description": "Specifies the static information collected about the host machine CMake is being run from. Only included when enabled by the v1 Query Files.",
"properties": {
"OSName": {
"description": "The host operating system name.",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"OSPlatform": {
"description": "The name of the CPU CMake is running on.",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"OSRelease": {
"description": "The OS sub-type (e.g., 'Professional' on Windows).",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"OSVersion": {
"description": "The OS build ID.",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"familyId": {
"description": "The processor family name.",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"hostname": {
"description": "Hostname.",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"is64Bits": {
"type": "boolean",
"description": "True if processor is 64 bit."
},
"modelId": {
"description": "The processor model ID",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"numberOfLogicalCPU": {
"description": "Number of logical cores.",
"$ref": "#/definitions/positiveIntegerOrNull"
},
"numberOfPhysicalCPU": {
"description": "Number of physical cores.",
"$ref": "#/definitions/positiveIntegerOrNull"
},
"processorAPICID": {
"description": "The processor APIC ID.",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"processorCacheSize": {
"description": "The processor L1 cache size.",
"$ref": "#/definitions/positiveIntegerOrNull"
},
"processorClockFrequency": {
"description": "The processor clock frequency.",
"anyOf": [
{
"type": "number",
"minimum": 1
},
{
"type": "null"
}
]
},
"processorName": {
"description": "Human readable processor name.",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"totalPhysicalMemory": {
"description": "Total physical memory in MiB",
"$ref": "#/definitions/positiveIntegerOrNull"
},
"totalVirtualMemory": {
"description": "Total virtual memory in MiB",
"$ref": "#/definitions/positiveIntegerOrNull"
},
"vendorID": {
"description": "The processor vendor ID.",
"$ref": "#/definitions/nonEmptyStringOrNull"
},
"vendorString": {
"description": "The processor vendor string.",
"$ref": "#/definitions/nonEmptyStringOrNull"
}
}
}
}
}
@@ -0,0 +1,109 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"dependencies": {
"type": "array",
"items": {
"type": "object",
"description": "Information about a single dependency.",
"properties": {
"name": {
"type": "string",
"description": "The name of the dependency."
},
"type": {
"type": "string",
"description": "The type of the dependency.",
"enum": [
"system",
"bundled"
]
},
"version": {
"type": "string",
"description": "The version of the dependency if available."
},
"via": {
"type": "string",
"description": "The source from which the dependency is came from. Not presented for direct CMake dependencies."
}
},
"required": [
"name",
"type"
],
"additionalProperties": false
},
"additionalItems": false
},
"program": {
"type": "object",
"description": "Information about the CMake tool.",
"properties": {
"name": {
"type": "string",
"description": "The name of the CMake tool."
},
"version": {
"type": "object",
"description": "Information about the version of the CMake tool.",
"properties": {
"major": {
"type": "integer",
"description": "The major version of the CMake tool."
},
"minor": {
"type": "integer",
"description": "The minor version of the CMake tool."
},
"patch": {
"type": "integer",
"description": "The patch version of the CMake tool."
},
"string": {
"type": "string",
"description": "The full version string of the CMake tool."
}
},
"required": [
"major",
"minor",
"patch",
"string"
],
"additionalProperties": false
}
},
"required": [
"name",
"version"
],
"additionalProperties": false
},
"version": {
"type": "object",
"properties": {
"major": {
"type": "integer",
"description": "The major version of the JSON output format."
},
"minor": {
"type": "integer",
"description": "The minor version of the JSON output format."
}
},
"required": [
"major",
"minor"
],
"additionalProperties": false
}
},
"required": [
"dependencies",
"program",
"version"
],
"additionalProperties": false
}
@@ -0,0 +1,565 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Schema for the CMake codemodel object kind",
"type": "object",
"required": [
"kind",
"version",
"paths",
"configurations"
],
"oneOf": [
{
"$ref": "#/definitions/codemodelV2_0"
},
{
"$ref": "#/definitions/codemodelV2_3"
},
{
"$ref": "#/definitions/codemodelV2_9"
}
],
"definitions": {
"kind": {
"type": "string",
"const": "codemodel",
"description": "Specifies the object kind"
},
"versionV2_0": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 2
},
"minor": {
"type": "integer",
"minimum": 0,
"maximum": 2
}
},
"additionalProperties": false
},
"versionV2_3": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 2
},
"minor": {
"type": "integer",
"minimum": 3,
"maximum": 8
}
},
"additionalProperties": false
},
"versionV2_9": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 2
},
"minor": {
"type": "integer",
"minimum": 9
}
},
"additionalProperties": false
},
"paths": {
"type": "object",
"required": [
"source",
"build"
],
"properties": {
"source": {
"type": "string",
"description": "Absolute path to the top-level source directory"
},
"build": {
"type": "string",
"description": "Absolute path to the top-level build directory"
}
},
"additionalProperties": false
},
"configurationDirectoryItemSource": {
"type": "string",
"description": "Path to the source directory. If it is inside the top level source directory, the path will be relative to that directory. For the top level source directory, this will simply be '.'. Paths outside the top level source directory will be absolute."
},
"configurationDirectoryItemBuild": {
"type": "string",
"description": "Path to the build directory. If it is inside the top level build directory, the path will be relative to that directory. For the top level build directory, this will simply be '.'. Paths outside the top level build directory will be absolute."
},
"configurationDirectoryItemParentIndex": {
"type": "integer",
"minimum": 0,
"description": "Index of the parent directory in the directories array"
},
"configurationDirectoryItemChildIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices of child directories"
},
"configurationDirectoryItemProjectIndex": {
"type": "integer",
"minimum": 0,
"description": "Index into the projects array"
},
"configurationDirectoryItemBuildSystemTargetIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices into the targets array"
},
"configurationDirectoryItemAbstractTargetIndexesV2_9": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices into the abstractTargets array"
},
"configurationDirectoryItemMinimumCMakeVersion": {
"type": "object",
"required": [
"string"
],
"properties": {
"string": {
"type": "string",
"description": "Minimum required CMake version, if known"
}
},
"additionalProperties": false
},
"configurationDirectoryItemHasInstallRule": {
"type": "boolean",
"description": "Whether the directory has install rules"
},
"configurationDirectoryItemJsonFileV2_3": {
"jsonFile": {
"type": "string",
"description": "Path to directory-specific JSON file"
}
},
"configurationDirectoriesV2_0": {
"type": "array",
"items": {
"type": "object",
"required": [
"source",
"build",
"projectIndex"
],
"properties": {
"source": {
"$ref": "#/definitions/configurationDirectoryItemSource"
},
"build": {
"$ref": "#/definitions/configurationDirectoryItemBuild"
},
"parentIndex": {
"$ref": "#/definitions/configurationDirectoryItemParentIndex"
},
"childIndexes": {
"$ref": "#/definitions/configurationDirectoryItemChildIndexes"
},
"projectIndex": {
"$ref": "#/definitions/configurationDirectoryItemProjectIndex"
},
"targetIndexes": {
"$ref": "#/definitions/configurationDirectoryItemBuildSystemTargetIndexes"
},
"minimumCMakeVersion": {
"$ref": "#/definitions/configurationDirectoryItemMinimumCMakeVersion"
},
"hasInstallRule": {
"$ref": "#/definitions/configurationDirectoryItemHasInstallRule"
}
},
"additionalProperties": false
}
},
"configurationDirectoriesV2_3": {
"type": "array",
"items": {
"type": "object",
"required": [
"source",
"build",
"projectIndex"
],
"properties": {
"source": {
"$ref": "#/definitions/configurationDirectoryItemSource"
},
"build": {
"$ref": "#/definitions/configurationDirectoryItemBuild"
},
"parentIndex": {
"$ref": "#/definitions/configurationDirectoryItemParentIndex"
},
"childIndexes": {
"$ref": "#/definitions/configurationDirectoryItemChildIndexes"
},
"projectIndex": {
"$ref": "#/definitions/configurationDirectoryItemProjectIndex"
},
"targetIndexes": {
"$ref": "#/definitions/configurationDirectoryItemBuildSystemTargetIndexes"
},
"minimumCMakeVersion": {
"$ref": "#/definitions/configurationDirectoryItemMinimumCMakeVersion"
},
"hasInstallRule": {
"$ref": "#/definitions/configurationDirectoryItemHasInstallRule"
},
"jsonFile": {
"$ref": "#/definitions/configurationDirectoryItemJsonFileV2_3"
}
},
"additionalProperties": false
}
},
"configurationDirectoriesV2_9": {
"type": "array",
"items": {
"type": "object",
"required": [
"source",
"build",
"projectIndex"
],
"properties": {
"source": {
"$ref": "#/definitions/configurationDirectoryItemSource"
},
"build": {
"$ref": "#/definitions/configurationDirectoryItemBuild"
},
"parentIndex": {
"$ref": "#/definitions/configurationDirectoryItemParentIndex"
},
"childIndexes": {
"$ref": "#/definitions/configurationDirectoryItemChildIndexes"
},
"projectIndex": {
"$ref": "#/definitions/configurationDirectoryItemProjectIndex"
},
"targetIndexes": {
"$ref": "#/definitions/configurationDirectoryItemBuildSystemTargetIndexes"
},
"abstractTargetIndexes": {
"$ref": "#/definitions/configurationDirectoryItemAbstractTargetIndexesV2_9"
},
"minimumCMakeVersion": {
"$ref": "#/definitions/configurationDirectoryItemMinimumCMakeVersion"
},
"hasInstallRule": {
"$ref": "#/definitions/configurationDirectoryItemHasInstallRule"
},
"jsonFile": {
"$ref": "#/definitions/configurationDirectoryItemJsonFileV2_3"
}
},
"additionalProperties": false
}
},
"configurationName": {
"type": "string",
"description": "Configuration name (e.g., 'Debug')"
},
"configurationProjects": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"directoryIndexes"
],
"properties": {
"name": {
"type": "string",
"description": "Project name"
},
"parentIndex": {
"type": "integer",
"minimum": 0,
"description": "Index of parent project"
},
"childIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices of child projects"
},
"directoryIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices into directories array"
},
"targetIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices into targets array"
}
}
}
},
"configurationProjectsV2_9": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"directoryIndexes"
],
"properties": {
"name": {
"type": "string",
"description": "Project name"
},
"parentIndex": {
"type": "integer",
"minimum": 0,
"description": "Index of parent project"
},
"childIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices of child projects"
},
"directoryIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices into directories array"
},
"targetIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices into targets array"
},
"abstractTargetIndexes": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0
},
"description": "Indices into abstractTargets array"
}
}
}
},
"configurationTargets": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"directoryIndex",
"projectIndex",
"jsonFile"
],
"properties": {
"name": {
"type": "string",
"description": "Target name"
},
"id": {
"type": "string",
"description": "Unique target identifier"
},
"directoryIndex": {
"type": "integer",
"minimum": 0,
"description": "Index into directories array"
},
"projectIndex": {
"type": "integer",
"minimum": 0,
"description": "Index into projects array"
},
"jsonFile": {
"type": "string",
"description": "Path to target-specific JSON file"
}
}
}
},
"configurationsV2_0": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"directories",
"projects",
"targets"
],
"properties": {
"name": {
"$ref": "#/definitions/configurationName"
},
"projects": {
"$ref": "#/definitions/configurationProjects"
},
"targets": {
"$ref": "#/definitions/configurationTargets"
},
"directories": {
"$ref": "#/definitions/configurationDirectoriesV2_0"
}
},
"additionalProperties": false
}
},
"configurationsV2_3": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"directories",
"projects",
"targets"
],
"properties": {
"name": {
"$ref": "#/definitions/configurationName"
},
"projects": {
"$ref": "#/definitions/configurationProjects"
},
"targets": {
"$ref": "#/definitions/configurationTargets"
},
"directories": {
"$ref": "#/definitions/configurationDirectoriesV2_3"
}
},
"additionalProperties": false
}
},
"configurationsV2_9": {
"type": "array",
"items": {
"type": "object",
"required": [
"name",
"directories",
"projects",
"targets",
"abstractTargets"
],
"properties": {
"name": {
"$ref": "#/definitions/configurationName"
},
"projects": {
"$ref": "#/definitions/configurationProjectsV2_9"
},
"targets": {
"$ref": "#/definitions/configurationTargets"
},
"abstractTargets": {
"$ref": "#/definitions/configurationTargets"
},
"directories": {
"$ref": "#/definitions/configurationDirectoriesV2_9"
}
},
"additionalProperties": false
}
},
"codemodelV2_0": {
"properties": {
"kind": {
"$ref": "#/definitions/kind"
},
"version": {
"$ref": "#/definitions/versionV2_0"
},
"paths": {
"$ref": "#/definitions/paths"
},
"configurations": {
"$ref": "#/definitions/configurationsV2_0"
}
},
"additionalProperties": false
},
"codemodelV2_3": {
"properties": {
"kind": {
"$ref": "#/definitions/kind"
},
"version": {
"$ref": "#/definitions/versionV2_3"
},
"paths": {
"$ref": "#/definitions/paths"
},
"configurations": {
"$ref": "#/definitions/configurationsV2_3"
}
},
"additionalProperties": false
},
"codemodelV2_9": {
"properties": {
"kind": {
"$ref": "#/definitions/kind"
},
"version": {
"$ref": "#/definitions/versionV2_9"
},
"paths": {
"$ref": "#/definitions/paths"
},
"configurations": {
"$ref": "#/definitions/configurationsV2_9"
}
},
"additionalProperties": false
}
}
}
@@ -0,0 +1,121 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"required": ["kind", "version", "backtraceGraph", "tests"],
"properties": {
"kind": {
"type": "string",
"const": "ctestInfo"
},
"version": {
"type": "object",
"required": ["major", "minor"],
"properties": {
"major": {
"const": 1,
"description": "A positive integer specifying the major version component of the JSON object model."
},
"minor": {
"const": 0,
"description": "A non-negative integer specifying the minor version component of the JSON object model."
}
}
},
"backtraceGraph": {
"type": "object",
"required": ["commands", "files", "nodes"],
"properties": {
"commands": {
"type": "array",
"description": "List of CMake command names.",
"items": {
"type": "string"
}
},
"files": {
"type": "array",
"description": "List of file paths, which may be relative or absolute. Relative paths are relative to the top-level source directory.",
"items": {
"type": "string"
}
},
"nodes": {
"type": "array",
"items": {
"type": "object",
"required": ["file"],
"properties": {
"command": {
"type": "integer",
"minimum": 0,
"description": "An optional member present when the node represents a command invocation within the file. The value is an unsigned integer 0-based index into the commands member of the backtraceGraph."
},
"file": {
"type": "integer",
"minimum": 0,
"description": "An unsigned integer 0-based index into the files member of the backtraceGraph."
},
"line": {
"type": "integer",
"minimum": 1,
"description": "An optional member present when the node represents a line within the file. The value is an unsigned integer 1-based line number in the file where the backtrace was added."
},
"parent": {
"type": "integer",
"minimum": 0,
"description": "An optional member present when the node is not the bottom of the call stack. The value is an unsigned integer 0-based index into the nodes member of the backtraceGraph representing the parent in the graph."
}
}
}
}
}
},
"tests": {
"type": "array",
"items": {
"type": "object",
"required": ["name", "backtrace"],
"properties": {
"name": {
"type": "string",
"description": "Test name",
"minLength": 1
},
"config": {
"type": "string",
"description": "Optional field specifying the configuration for which the test will run. This will always match the -C option specified on the ctest command line. If no such option was given, this field will not be present."
},
"command": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"description": "Optional array where the first element is the test command and the remaining elements are the command arguments. Normally, this field should be present and non-empty, but in certain corner cases involving generator expressions, it is possible for a test to have no command and therefore this field can be missing."
},
"backtrace": {
"type": "integer",
"description": "Index into the nodes member of the backtraceGraph."
},
"properties": {
"type": "array",
"description": "Optional list of test properties associated with the test.",
"items": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Test property name.",
"minLength": 1
},
"value": {
"description": "Value of the test property. Any valid JSON type might be present."
}
}
}
}
}
}
}
}
}
@@ -0,0 +1,636 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Schema for the CMake codemodel directory object",
"type": "object",
"oneOf": [
{
"$comment": "The top level codemodelVersion field was only added in version 2.9, so we can't differentiate between earlier versions",
"anyOf": [
{
"$ref": "#/definitions/codemodelV2_0"
},
{
"$ref": "#/definitions/codemodelV2_4"
},
{
"$ref": "#/definitions/codemodelV2_5"
}
]
},
{
"$ref": "#/definitions/codemodelV2_9"
}
],
"definitions": {
"codemodelVersionV2_9": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 2
},
"minor": {
"type": "integer",
"minimum": 9
}
},
"additionalProperties": false
},
"backtraceGraph": {
"type": "object",
"required": [
"nodes",
"commands",
"files"
],
"properties": {
"nodes": {
"type": "array",
"items": {
"type": "object",
"required": [
"file"
],
"properties": {
"file": {
"type": "integer",
"minimum": 0,
"description": "0-based index into the backtrace files array"
},
"line": {
"type": "integer",
"minimum": 1,
"description": "This is present when the node represents a line within the file. The line number is a 1-based value."
},
"command": {
"type": "integer",
"minimum": 0,
"description": "This is present when the node represents a command invocation. It is a 0-based index into the backtrace commands array."
},
"parent": {
"type": "integer",
"minimum": 0,
"description": "This is present when the node is not the bottom of the call stack. It is a 0-based index of another node in the backtrace nodes array."
}
},
"additionalProperties": false
}
},
"commands": {
"type": "array",
"description": "Each list item is a string specifying a command name",
"items": {
"type": "string"
}
},
"files": {
"type": "array",
"description": "Each list item is a string specifying the path to a file, represented with forward slashes. If the file is inside the top level source directory, the path is specified relative to that directory. Otherwise, the path is absolute.",
"items": {
"type": "string"
}
}
},
"additionalProperties": false
},
"paths": {
"type": "object",
"required": [
"source",
"build"
],
"properties": {
"source": {
"type": "string",
"description": "Path to the source directory. If it is inside the top level source directory, the path will be relative to that directory. For the top level source directory, this will simply be '.'. Paths outside the top level source directory will be absolute."
},
"build": {
"type": "string",
"description": "Path to the build directory. If it is inside the top level build directory, the path will be relative to that directory. For the top level build directory, this will simply be '.'. Paths outside the top level build directory will be absolute."
}
},
"additionalProperties": false
},
"installerComponent": {
"type": "string",
"description": "Specifies the component selected by the corresponding install command invocation"
},
"installerDestination": {
"type": "string",
"description": "The install destination path. May be absolute or relative to the install prefix"
},
"installerPaths": {
"type": "array",
"description": "Paths (files or directories) to be installed",
"items": {
"oneOf": [
{
"type": "string",
"description": "Path from which a file/directory is installed, also specifying the install path"
},
{
"type": "object",
"properties": {
"from": {
"type": "string",
"description": "Path from which a file/directory is installed"
},
"to": {
"type": "string",
"description": "Path to which the file/directory is installed under the destination"
}
},
"required": [
"from",
"to"
]
}
]
}
},
"installerItemTypesV2_0": {
"type": "string",
"enum": [
"file",
"directory",
"target",
"export",
"script",
"code",
"importedRuntimeArtifacts",
"runtimeDependencySet"
]
},
"installerItemTypesV2_4": {
"type": "string",
"enum": [
"fileSet"
]
},
"installerItemTypesV2_5": {
"type": "string",
"enum": [
"cxxModuleBmi"
]
},
"installerTypeV2_0": {
"$ref": "#/definitions/installerItemTypesV2_0",
"description": "Type of installation rule"
},
"installerTypeV2_4": {
"anyOf": [
{
"$ref": "#/definitions/installerItemTypesV2_0"
},
{
"$ref": "#/definitions/installerItemTypesV2_4"
}
],
"description": "Type of installation rule"
},
"installerTypeV2_5": {
"anyOf": [
{
"$ref": "#/definitions/installerItemTypesV2_0"
},
{
"$ref": "#/definitions/installerItemTypesV2_4"
},
{
"$ref": "#/definitions/installerItemTypesV2_5"
}
],
"description": "Type of installation rule"
},
"installerIsExcludeFromAll": {
"type": "boolean",
"description": "Present when install is called with EXCLUDE_FROM_ALL option"
},
"installerIsForAllComponents": {
"type": "boolean",
"description": "Present when install(SCRIPT|CODE) is called with ALL_COMPONENTS option"
},
"installerIsOptional": {
"type": "boolean",
"description": "Present when install is called with OPTIONAL option"
},
"installerTargetId": {
"type": "string",
"description": "Uniquely identifying string for the target to be installed"
},
"installerTargetIndex": {
"type": "integer",
"minimum": 0,
"description": "0-based index into the codemodel targets array"
},
"installerTargetIsImportLibrary": {
"type": "boolean",
"description": "Present for Windows DLL import library or AIX linker import file"
},
"installerTargetInstallNamelink": {
"type": "string",
"enum": [
"skip",
"only"
],
"description": "How to handle symlinks for VERSION/SOVERSION target properties"
},
"installerExportName": {
"type": "string",
"description": "Name of the export for export type"
},
"installerExportTargets": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "String uniquely identifying the target"
},
"index": {
"type": "integer",
"minimum": 0,
"description": "0-based index into the codemodel targets array"
}
},
"additionalProperties": false,
"required": [
"id",
"index"
]
}
},
"installerRuntimeDependencySetName": {
"type": "string",
"description": "Name of the runtime dependency set"
},
"installerRuntimeDependencySetType": {
"type": "string",
"enum": [
"library",
"framework"
],
"description": "Type of runtime dependency set"
},
"installerScriptFile": {
"type": "string",
"description": "Path to the script file on disk"
},
"installerBacktrace": {
"type": "integer",
"minimum": 0,
"description": "0-based index into the backtraceGraph nodes array"
},
"installerFileSetNameV2_4": {
"type": "string",
"description": "Name of the file set"
},
"installerFileSetTypeV2_4": {
"type": "string",
"description": "Type of the file set"
},
"installerFileSetDirectoriesV2_4": {
"type": "array",
"items": {
"type": "string"
},
"description": "File set's base directories"
},
"installerFileSetTargetV2_4": {
"type": "object",
"required": [
"id",
"index"
],
"properties": {
"id": {
"type": "string",
"description": "String uniquely identifying the target"
},
"index": {
"type": "integer",
"minimum": 0,
"description": "0-based index into the codemodel targets array"
}
},
"additionalProperties": false
},
"installerCxxModuleBmiTargetV2_5": {
"type": "object",
"properties": {
"id": {
"type": "string"
},
"index": {
"type": "integer",
"minimum": 0
}
},
"additionalProperties": false
},
"installersV2_0": {
"type": "array",
"items": {
"type": "object",
"required": [
"component",
"type"
],
"properties": {
"component": {
"$ref": "#/definitions/installerComponent"
},
"destination": {
"$ref": "#/definitions/installerDestination"
},
"paths": {
"$ref": "#/definitions/installerPaths"
},
"type": {
"$ref": "#/definitions/installerTypeV2_0"
},
"isExcludeFromAll": {
"$ref": "#/definitions/installerIsExcludeFromAll"
},
"isForAllComponents": {
"$ref": "#/definitions/installerIsForAllComponents"
},
"isOptional": {
"$ref": "#/definitions/installerIsOptional"
},
"targetId": {
"$ref": "#/definitions/installerTargetId"
},
"targetIndex": {
"$ref": "#/definitions/installerTargetIndex"
},
"targetIsImportLibrary": {
"$ref": "#/definitions/installerTargetIsImportLibrary"
},
"targetInstallNamelink": {
"$ref": "#/definitions/installerTargetInstallNamelink"
},
"exportName": {
"$ref": "#/definitions/installerExportName"
},
"exportTargets": {
"$ref": "#/definitions/installerExportTargets"
},
"runtimeDependencySetName": {
"$ref": "#/definitions/installerRuntimeDependencySetName"
},
"runtimeDependencySetType": {
"$ref": "#/definitions/installerRuntimeDependencySetType"
},
"scriptFile": {
"$ref": "#/definitions/installerScriptFile"
},
"backtrace": {
"$ref": "#/definitions/installerBacktrace"
}
},
"additionalProperties": false
}
},
"installersV2_4": {
"type": "array",
"items": {
"type": "object",
"required": [
"component",
"type"
],
"properties": {
"component": {
"$ref": "#/definitions/installerComponent"
},
"destination": {
"$ref": "#/definitions/installerDestination"
},
"paths": {
"$ref": "#/definitions/installerPaths"
},
"type": {
"$ref": "#/definitions/installerTypeV2_0"
},
"isExcludeFromAll": {
"$ref": "#/definitions/installerIsExcludeFromAll"
},
"isForAllComponents": {
"$ref": "#/definitions/installerIsForAllComponents"
},
"isOptional": {
"$ref": "#/definitions/installerIsOptional"
},
"targetId": {
"$ref": "#/definitions/installerTargetId"
},
"targetIndex": {
"$ref": "#/definitions/installerTargetIndex"
},
"targetIsImportLibrary": {
"$ref": "#/definitions/installerTargetIsImportLibrary"
},
"targetInstallNamelink": {
"$ref": "#/definitions/installerTargetInstallNamelink"
},
"exportName": {
"$ref": "#/definitions/installerExportName"
},
"exportTargets": {
"$ref": "#/definitions/installerExportTargets"
},
"runtimeDependencySetName": {
"$ref": "#/definitions/installerRuntimeDependencySetName"
},
"runtimeDependencySetType": {
"$ref": "#/definitions/installerRuntimeDependencySetType"
},
"scriptFile": {
"$ref": "#/definitions/installerScriptFile"
},
"backtrace": {
"$ref": "#/definitions/installerBacktrace"
},
"fileSetName": {
"$ref": "#/definitions/installerFileSetNameV2_4"
},
"fileSetType": {
"$ref": "#/definitions/installerFileSetTypeV2_4"
},
"fileSetDirectories": {
"$ref": "#/definitions/installerFileSetDirectoriesV2_4"
},
"fileSetTarget": {
"$ref": "#/definitions/installerFileSetTargetV2_4"
}
},
"additionalProperties": false
}
},
"installersV2_5": {
"type": "array",
"items": {
"type": "object",
"required": [
"component",
"type"
],
"properties": {
"component": {
"$ref": "#/definitions/installerComponent"
},
"destination": {
"$ref": "#/definitions/installerDestination"
},
"paths": {
"$ref": "#/definitions/installerPaths"
},
"type": {
"$ref": "#/definitions/installerTypeV2_5"
},
"isExcludeFromAll": {
"$ref": "#/definitions/installerIsExcludeFromAll"
},
"isForAllComponents": {
"$ref": "#/definitions/installerIsForAllComponents"
},
"isOptional": {
"$ref": "#/definitions/installerIsOptional"
},
"targetId": {
"$ref": "#/definitions/installerTargetId"
},
"targetIndex": {
"$ref": "#/definitions/installerTargetIndex"
},
"targetIsImportLibrary": {
"$ref": "#/definitions/installerTargetIsImportLibrary"
},
"targetInstallNamelink": {
"$ref": "#/definitions/installerTargetInstallNamelink"
},
"exportName": {
"$ref": "#/definitions/installerExportName"
},
"exportTargets": {
"$ref": "#/definitions/installerExportTargets"
},
"runtimeDependencySetName": {
"$ref": "#/definitions/installerRuntimeDependencySetName"
},
"runtimeDependencySetType": {
"$ref": "#/definitions/installerRuntimeDependencySetType"
},
"scriptFile": {
"$ref": "#/definitions/installerScriptFile"
},
"backtrace": {
"$ref": "#/definitions/installerBacktrace"
},
"fileSetName": {
"$ref": "#/definitions/installerFileSetNameV2_4"
},
"fileSetType": {
"$ref": "#/definitions/installerFileSetTypeV2_4"
},
"fileSetDirectories": {
"$ref": "#/definitions/installerFileSetDirectoriesV2_4"
},
"fileSetTarget": {
"$ref": "#/definitions/installerFileSetTargetV2_4"
},
"cxxModuleBmiTarget": {
"$ref": "#/definitions/installerCxxModuleBmiTargetV2_5"
}
},
"additionalProperties": false
}
},
"codemodelV2_0": {
"required": [
"backtraceGraph",
"paths",
"installers"
],
"properties": {
"backtraceGraph": {
"$ref": "#/definitions/backtraceGraph"
},
"paths": {
"$ref": "#/definitions/paths"
},
"installers": {
"$ref": "#/definitions/installersV2_0"
}
},
"additionalProperties": false
},
"codemodelV2_4": {
"required": [
"backtraceGraph",
"paths",
"installers"
],
"properties": {
"backtraceGraph": {
"$ref": "#/definitions/backtraceGraph"
},
"paths": {
"$ref": "#/definitions/paths"
},
"installers": {
"$ref": "#/definitions/installersV2_4"
}
},
"additionalProperties": false
},
"codemodelV2_5": {
"required": [
"backtraceGraph",
"paths",
"installers"
],
"properties": {
"backtraceGraph": {
"$ref": "#/definitions/backtraceGraph"
},
"paths": {
"$ref": "#/definitions/paths"
},
"installers": {
"$ref": "#/definitions/installersV2_5"
}
},
"additionalProperties": false
},
"codemodelV2_9": {
"required": [
"codemodelVersion",
"backtraceGraph",
"paths",
"installers"
],
"properties": {
"codemodelVersion": {
"$ref": "#/definitions/codemodelVersionV2_9"
},
"backtraceGraph": {
"$ref": "#/definitions/backtraceGraph"
},
"paths": {
"$ref": "#/definitions/paths"
},
"installers": {
"$ref": "#/definitions/installersV2_5"
}
},
"additionalProperties": false
}
}
}
@@ -0,0 +1,527 @@
{
"$schema": "http://json-schema.org/draft/2020-12/schema#",
"oneOf": [
{
"$ref": "#/definitions/snippetV1_0"
},
{
"$ref": "#/definitions/snippetV1_1"
}
],
"definitions": {
"snippetConditionals": {
"allOf": [
{
"if": {
"properties": {
"role": {
"enum": [
"configure",
"generate",
"compile",
"link",
"custom",
"cmakeBuild",
"cmakeInstall",
"install",
"ctest",
"test"
]
}
},
"required": [
"role"
]
},
"then": {
"required": [
"command"
]
}
},
{
"if": {
"properties": {
"role": {
"enum": [
"compile",
"link"
]
}
},
"required": [
"role"
]
},
"then": {
"required": [
"language",
"target",
"outputs",
"outputSizes"
]
}
},
{
"if": {
"properties": {
"role": {
"const": "compile"
}
},
"required": [
"role"
]
},
"then": {
"required": [
"source"
]
}
},
{
"if": {
"properties": {
"role": {
"const": "custom"
}
},
"required": [
"role"
]
},
"then": {
"required": [
"outputs",
"outputSizes"
]
}
},
{
"if": {
"properties": {
"role": {
"enum": [
"compile",
"link",
"custom",
"install",
"test"
]
}
},
"required": [
"role"
]
},
"then": {
"required": [
"config"
]
}
},
{
"if": {
"properties": {
"role": {
"const": "ctest"
}
},
"required": [
"role"
]
},
"then": {
"required": [
"showOnly"
]
}
},
{
"if": {
"properties": {
"role": {
"const": "test"
}
},
"required": [
"role"
]
},
"then": {
"required": [
"testName"
]
}
}
]
},
"versionV1_0": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"const": 0
}
},
"additionalProperties": false
},
"versionV1_1": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"const": 1
}
},
"additionalProperties": false
},
"fields": {
"command": {
"type": "string",
"description": "The full command executed. Excluded when role is build.",
"minLength": 1
},
"workingDir": {
"type": "string",
"description": "The working directory in which the command was executed.",
"minLength": 1
},
"result": {
"description": "The exit code of the command, or null when unavailable.",
"anyOf": [
{
"type": "integer"
},
{
"type": "null"
}
]
},
"role": {
"type": "string",
"description": "The type of command executed.",
"enum": [
"configure",
"generate",
"compile",
"link",
"custom",
"build",
"cmakeBuild",
"cmakeInstall",
"install",
"ctest",
"test"
]
},
"target": {
"type": "string",
"description": "The CMake target associated with the command.",
"minLength": 1
},
"targetLabels": {
"type": "array",
"description": "Optional labels associated with the target.",
"items": {
"type": "string"
}
},
"timeStart": {
"type": "integer",
"description": "Command start time in milliseconds since epoch.",
"minimum": 0
},
"duration": {
"type": "integer",
"description": "Command duration in milliseconds.",
"minimum": 0
},
"outputs": {
"type": "array",
"description": "The command output file paths.",
"items": {
"type": "string",
"minLength": 1
}
},
"outputSizes": {
"type": "array",
"description": "Sizes in bytes for each output file.",
"items": {
"type": "integer",
"minimum": 0
}
},
"source": {
"type": "string",
"description": "The source file being compiled.",
"minLength": 1
},
"language": {
"type": "string",
"description": "The language used by the compile or link command.",
"minLength": 1
},
"testName": {
"type": "string",
"description": "The name of the test being executed.",
"minLength": 1
},
"config": {
"type": "string",
"description": "The build configuration, such as Release or Debug. May be empty for some test runs."
},
"dynamicSystemInformation": {
"type": "object",
"description": "Dynamic host information collected before and after command execution.",
"required": [
"beforeHostMemoryUsed",
"afterHostMemoryUsed",
"beforeCPULoadAverage",
"afterCPULoadAverage"
],
"properties": {
"beforeHostMemoryUsed": {
"type": "number",
"description": "Host memory used in KiB at command start.",
"minimum": 0
},
"afterHostMemoryUsed": {
"type": "number",
"description": "Host memory used in KiB at command end.",
"minimum": 0
},
"beforeCPULoadAverage": {
"description": "Average CPU load at command start.",
"anyOf": [
{
"type": "number"
},
{
"type": "null"
}
]
},
"afterCPULoadAverage": {
"description": "Average CPU load at command end.",
"anyOf": [
{
"type": "number"
},
{
"type": "null"
}
]
}
}
},
"cmakeContent": {
"description": "Relative path to the corresponding v1 CMake content file.",
"anyOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
},
"showOnly": {
"type": "boolean",
"description": "True when ctest was invoked with --show-only."
},
"stdout": {
"type": "string",
"description": "The standard output produced by the command."
},
"stderr": {
"type": "string",
"description": "The standard error output produced by the command."
},
"traceFile": {
"description": "A path, relative to the data directory, referencing a copied JSON file generated by Clang's -ftime-trace option.",
"oneOf": [
{
"type": "string"
},
{
"type": "null"
}
]
}
},
"snippetV1_0": {
"type": "object",
"required": [
"version",
"role",
"result",
"timeStart",
"duration",
"workingDir"
],
"properties": {
"version": {
"$ref": "#/definitions/versionV1_0"
},
"command": {
"$ref": "#/definitions/fields/command"
},
"workingDir": {
"$ref": "#/definitions/fields/workingDir"
},
"result": {
"$ref": "#/definitions/fields/result"
},
"role": {
"$ref": "#/definitions/fields/role"
},
"target": {
"$ref": "#/definitions/fields/target"
},
"targetLabels": {
"$ref": "#/definitions/fields/targetLabels"
},
"timeStart": {
"$ref": "#/definitions/fields/timeStart"
},
"duration": {
"$ref": "#/definitions/fields/duration"
},
"outputs": {
"$ref": "#/definitions/fields/outputs"
},
"outputSizes": {
"$ref": "#/definitions/fields/outputSizes"
},
"source": {
"$ref": "#/definitions/fields/source"
},
"language": {
"$ref": "#/definitions/fields/language"
},
"testName": {
"$ref": "#/definitions/fields/testName"
},
"config": {
"$ref": "#/definitions/fields/config"
},
"dynamicSystemInformation": {
"$ref": "#/definitions/fields/dynamicSystemInformation"
},
"cmakeContent": {
"$ref": "#/definitions/fields/cmakeContent"
},
"showOnly": {
"$ref": "#/definitions/fields/showOnly"
}
},
"additionalProperties": false,
"allOf": [
{
"$ref": "#/definitions/snippetConditionals"
}
]
},
"snippetV1_1": {
"type": "object",
"required": [
"version",
"role",
"result",
"timeStart",
"duration",
"workingDir"
],
"properties": {
"version": {
"$ref": "#/definitions/versionV1_1"
},
"command": {
"$ref": "#/definitions/fields/command"
},
"workingDir": {
"$ref": "#/definitions/fields/workingDir"
},
"result": {
"$ref": "#/definitions/fields/result"
},
"role": {
"$ref": "#/definitions/fields/role"
},
"target": {
"$ref": "#/definitions/fields/target"
},
"targetLabels": {
"$ref": "#/definitions/fields/targetLabels"
},
"timeStart": {
"$ref": "#/definitions/fields/timeStart"
},
"duration": {
"$ref": "#/definitions/fields/duration"
},
"outputs": {
"$ref": "#/definitions/fields/outputs"
},
"outputSizes": {
"$ref": "#/definitions/fields/outputSizes"
},
"source": {
"$ref": "#/definitions/fields/source"
},
"language": {
"$ref": "#/definitions/fields/language"
},
"testName": {
"$ref": "#/definitions/fields/testName"
},
"config": {
"$ref": "#/definitions/fields/config"
},
"dynamicSystemInformation": {
"$ref": "#/definitions/fields/dynamicSystemInformation"
},
"cmakeContent": {
"$ref": "#/definitions/fields/cmakeContent"
},
"showOnly": {
"$ref": "#/definitions/fields/showOnly"
},
"stderr": {
"$ref": "#/definitions/fields/stderr"
},
"stdout": {
"$ref": "#/definitions/fields/stdout"
},
"traceFile": {
"$ref": "#/definitions/fields/traceFile"
}
},
"additionalProperties": false,
"allOf": [
{
"$ref": "#/definitions/snippetConditionals"
}
]
}
}
}
@@ -0,0 +1,55 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Schema for the CMake configureLog object kind",
"type": "object",
"required": [
"kind",
"version",
"path",
"eventKindNames"
],
"properties": {
"kind": {
"type": "string",
"const": "configureLog"
},
"version": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"const": 0
}
},
"additionalProperties": false
},
"path": {
"type": "string",
"description": "Path to the configure log file. Clients must read the log file from this path, which may be different to the path in CMake's documentation. The log file specified by this path might not exist if no events have been logged."
},
"eventKindNames": {
"type": "array",
"description": "Names of versioned event kinds included in the configure log. Other event kinds might be present in the configure log, but clients must ignore those not listed in this array.",
"items": {
"type": "string",
"enum": [
"message-v1",
"try_compile-v1",
"try_run-v1",
"find-v1",
"find_package-v1"
]
},
"uniqueItems": true
}
},
"additionalProperties": false
}
@@ -0,0 +1,78 @@
{
"$schema": "http://json-schema.org/draft/2020-12/schema#",
"type": "object",
"required": ["version"],
"properties": {
"version": {
"description": "The data version of snippet file to generate.",
"oneOf": [
{
"type": "integer",
"const": 1
},
{
"type": "object",
"required": [
"major"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"enum": [
0,
1
]
}
},
"additionalProperties": false
}
]
},
"callbacks": {
"type": "array",
"description": "A list of command-line strings for callbacks to handle collected instrumentation data. Whenever these callbacks are executed, the full path to a v1 Index File is appended to the arguments included in the string.",
"items": {
"type": "string"
}
},
"hooks": {
"type": "array",
"description": "A list of strings specifying when indexing should occur automatically. These are the intervals when instrumentation data should be collated and user callbacks should be invoked to handle the data.",
"items": {
"enum": [
"postGenerate",
"preBuild",
"postBuild",
"preCMakeBuild",
"postCMakeBuild",
"postCMakeInstall",
"postCMakeWorkflow",
"postCTest"
],
"type": "string"
},
"uniqueItems": true
},
"options": {
"type": "array",
"description": "A list of strings used to enable certain optional behavior, including the collection of certain additional data.",
"uniqueItems": true,
"items": {
"enum": [
"staticSystemInformation",
"dynamicSystemInformation",
"compileTrace",
"cdashSubmit",
"cdashVerbose",
"trace",
"captureOutput"
],
"type": "string"
}
}
}
}
@@ -0,0 +1,186 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"description": "Schema for the CMake cmakeFiles object kind",
"type": "object",
"required": [
"kind",
"version",
"paths",
"inputs"
],
"oneOf": [
{
"$ref": "#/definitions/cmakeFilesV1_0"
},
{
"$ref": "#/definitions/cmakeFilesV1_1"
}
],
"definitions": {
"kind": {
"type": "string",
"const": "cmakeFiles",
"description": "Specifies the object kind"
},
"versionV1_0": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"const": 0
}
},
"additionalProperties": false
},
"versionV1_1": {
"type": "object",
"required": [
"major",
"minor"
],
"properties": {
"major": {
"type": "integer",
"const": 1
},
"minor": {
"type": "integer",
"const": 1
}
},
"additionalProperties": false
},
"paths": {
"type": "object",
"required": [
"build",
"source"
],
"properties": {
"build": {
"type": "string",
"description": "Absolute path to the top-level build directory"
},
"source": {
"type": "string",
"description": "Absolute path to the top-level source directory"
}
},
"additionalProperties": false
},
"inputs": {
"type": "array",
"items": {
"type": "object",
"required": [
"path"
],
"properties": {
"path": {
"type": "string",
"description": "Path to an input file to CMake"
},
"isGenerated": {
"type": "boolean",
"description": "Indicates if the file is under the build directory in out-of-source builds"
},
"isExternal": {
"type": "boolean",
"description": "Indicates if the file is not under source or build directories"
},
"isCMake": {
"type": "boolean",
"description": "Indicates if the file is in the CMake installation"
}
},
"additionalProperties": false
}
},
"globsDependentV1_1": {
"type": "array",
"description": "Optional member present only when the project calls file(GLOB) or file(GLOB_RECURSE) with the CONFIGURE_DEPENDS option",
"items": {
"type": "object",
"required": [
"expression",
"paths"
],
"properties": {
"expression": {
"type": "string",
"description": "The globbing expression. If the result of the expression no longer matches the same list of paths, the build system is considered out of date and the build tool will re-run cmake."
},
"recurse": {
"type": "boolean",
"description": "This will be true if the glob expression was from a file(GLOB_RECURSE) call"
},
"listDirectories": {
"type": "boolean",
"description": "This will be true if the expression is from a file(GLOB) that does not specify LIST_DIRECTORIES false, or from a file(GLOB_RECURSE) with LIST_DIRECTORIES set to true"
},
"followSymlinks": {
"type": "boolean",
"description": "This will be true if the FOLLOW_SYMLINKS option was given"
},
"relative": {
"type": "string",
"description": "This will be present if the RELATIVE option was given. The value is the path given after the RELATIVE keyword."
},
"paths": {
"type": "array",
"items": {
"type": "string"
},
"description": "Paths matched by the globbing expression"
}
},
"additionalProperties": false
}
},
"cmakeFilesV1_0": {
"properties": {
"kind": {
"$ref": "#/definitions/kind"
},
"version": {
"$ref": "#/definitions/versionV1_0"
},
"paths": {
"$ref": "#/definitions/paths"
},
"inputs": {
"$ref": "#/definitions/inputs"
}
},
"additionalProperties": false
},
"cmakeFilesV1_1": {
"properties": {
"kind": {
"$ref": "#/definitions/kind"
},
"version": {
"$ref": "#/definitions/versionV1_1"
},
"paths": {
"$ref": "#/definitions/paths"
},
"inputs": {
"$ref": "#/definitions/inputs"
},
"globsDependent": {
"$ref": "#/definitions/globsDependentV1_1"
}
},
"additionalProperties": false
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

@@ -0,0 +1,33 @@
add_compile_definitions
-----------------------
.. versionadded:: 3.12
Add preprocessor definitions to the compilation of source files.
.. code-block:: cmake
add_compile_definitions(<definition> ...)
Adds preprocessor definitions to the compiler command line.
The preprocessor definitions are added to the :prop_dir:`COMPILE_DEFINITIONS`
directory property for the current ``CMakeLists`` file. They are also added to
the :prop_tgt:`COMPILE_DEFINITIONS` target property for each target in the
current ``CMakeLists`` file.
Definitions are specified using the syntax ``VAR`` or ``VAR=value``.
Function-style definitions are not supported. CMake will automatically
escape the value correctly for the native build system (note that CMake
language syntax may require escapes to specify some values).
.. versionadded:: 3.26
Any leading ``-D`` on an item will be removed.
.. |command_name| replace:: ``add_compile_definitions``
.. include:: include/GENEX_NOTE.rst
See Also
^^^^^^^^
* The command :command:`target_compile_definitions` adds target-specific definitions.
@@ -0,0 +1,68 @@
add_compile_options
-------------------
Add options to the compilation of source files.
.. code-block:: cmake
add_compile_options(<option> ...)
Adds options to the :prop_dir:`COMPILE_OPTIONS` directory property.
These options are used when compiling targets from the current
directory and below.
.. note::
These options are not used when linking.
See the :command:`add_link_options` command for that.
Arguments
^^^^^^^^^
.. |command_name| replace:: ``add_compile_options``
.. include:: include/GENEX_NOTE.rst
.. include:: include/OPTIONS_SHELL.rst
Example
^^^^^^^
Since different compilers support different options, a typical use of
this command is in a compiler-specific conditional clause:
.. code-block:: cmake
if (MSVC)
# warning level 4
add_compile_options(/W4)
else()
# additional warnings
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
To set per-language options, use the :genex:`$<COMPILE_LANGUAGE>`
or :genex:`$<COMPILE_LANGUAGE:languages> <COMPILE_LANGUAGE:languages>`
generator expressions.
See Also
^^^^^^^^
* This command can be used to add any options. However, for
adding preprocessor definitions and include directories it is recommended
to use the more specific commands :command:`add_compile_definitions`
and :command:`include_directories`.
* The command :command:`target_compile_options` adds target-specific options.
* This command adds compile options for all languages.
Use the :genex:`COMPILE_LANGUAGE` generator expression to specify
per-language compile options.
* The source file property :prop_sf:`COMPILE_OPTIONS` adds options to one
source file.
* :command:`add_link_options` adds options for linking.
* :variable:`CMAKE_<LANG>_FLAGS` and :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>`
add language-wide flags passed to all invocations of the compiler.
This includes invocations that drive compiling and those that drive linking.
@@ -0,0 +1,723 @@
add_custom_command
------------------
Add a custom build rule to the generated build system.
Synopsis
^^^^^^^^
.. parsed-literal::
`Generating Files`_
add_custom_command(`OUTPUT`_ <output1> [<output2> ...]
COMMAND <command1> [ARGS] [<args1>...]
[...])
`Build Events`_
add_custom_command(`TARGET`_ <target>
PRE_BUILD | PRE_LINK | POST_BUILD
[...])
Generating Files
^^^^^^^^^^^^^^^^
.. signature::
add_custom_command(OUTPUT <output1> [<output2> ...]
COMMAND <command1> [ARGS] [<args1>...]
[...])
Add a custom command to produce an output:
.. code-block:: cmake
add_custom_command(OUTPUT <output1> [<output2> ...]
COMMAND <command1> [ARGS] [<args1>...]
[COMMAND <command2> [ARGS] [<args2>...]] ...
[MAIN_DEPENDENCY depend]
[DEPENDS <depends>...]
[BYPRODUCTS <files>...]
[IMPLICIT_DEPENDS <lang1> <depend1>
[<lang2> <depend2>] ...]
[WORKING_DIRECTORY <dir>]
[COMMENT <comment>]
[DEPFILE <depfile>]
[JOB_POOL <job_pool>]
[JOB_SERVER_AWARE <bool>]
[VERBATIM] [APPEND] [USES_TERMINAL]
[CODEGEN]
[COMMAND_EXPAND_LISTS]
[DEPENDS_EXPLICIT_ONLY])
This defines a command to generate specified ``OUTPUT`` file(s).
A target created in the same directory (``CMakeLists.txt`` file)
that specifies any output of the custom command as a source file
is given a rule to generate the file using the command at build time.
Do not list the output in more than one independent target that
may build in parallel or the instances of the rule may conflict.
Instead, use the :command:`add_custom_target` command to drive the
command and make the other targets depend on that one. See the
`Example: Generating Files for Multiple Targets`_ below.
The options are:
``APPEND``
Append the ``COMMAND`` and ``DEPENDS`` option values to the custom
command for the first output specified. There must have already
been a previous call to this command with the same output.
If the previous call specified the output via a generator expression,
the output specified by the current call must match in at least one
configuration after evaluating generator expressions. In this case,
the appended commands and dependencies apply to all configurations.
The ``COMMENT``, ``MAIN_DEPENDENCY``, and ``WORKING_DIRECTORY``
options are currently ignored when ``APPEND`` is given, but may be
used in the future.
``BYPRODUCTS``
.. versionadded:: 3.2
Specify the files the command is expected to produce but whose
modification time may or may not be newer than the dependencies.
If a byproduct name is a relative path it will be interpreted
relative to the build tree directory corresponding to the
current source directory.
Each byproduct file will be marked with the :prop_sf:`GENERATED`
source file property automatically.
*See policy* :policy:`CMP0058` *for the motivation behind this feature.*
Explicit specification of byproducts is supported by the
:generator:`Ninja` generator to tell the ``ninja`` build tool
how to regenerate byproducts when they are missing. It is
also useful when other build rules (e.g. custom commands)
depend on the byproducts. Ninja requires a build rule for any
generated file on which another rule depends even if there are
order-only dependencies to ensure the byproducts will be
available before their dependents build.
The :ref:`Makefile Generators` will remove ``BYPRODUCTS`` and other
:prop_sf:`GENERATED` files during ``make clean``.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
All byproducts must be set in the first call to
``add_custom_command(OUTPUT...)`` for the output files.
.. versionadded:: 3.20
Arguments to ``BYPRODUCTS`` may use a restricted set of
:manual:`generator expressions <cmake-generator-expressions(7)>`.
:ref:`Target-dependent expressions <Target-Dependent Expressions>`
are not permitted.
.. versionchanged:: 3.28
In targets using :ref:`file sets`, custom command byproducts are now
considered private unless they are listed in a non-private file set.
See policy :policy:`CMP0154`.
``COMMAND``
Specify the command-line(s) to execute at build time.
At least one ``COMMAND`` would normally be given, but certain patterns
may omit it, such as adding commands in separate calls using ``APPEND``.
If more than one ``COMMAND`` is specified, they will be executed in order,
but *not* necessarily composed into a stateful shell or batch script.
To run a full script, use the :command:`configure_file` command or the
:command:`file(GENERATE)` command to create it, and then specify
a ``COMMAND`` to launch it.
The optional ``ARGS`` argument is for backward compatibility and
will be ignored.
If ``COMMAND`` specifies an executable target name (created by the
:command:`add_executable` command), it will automatically be replaced
by the location of the executable created at build time if either of
the following is true:
* The target is not being cross-compiled (i.e. the
:variable:`CMAKE_CROSSCOMPILING` variable is not set to true).
* .. versionadded:: 3.6
The target is being cross-compiled and an emulator is provided (i.e.
its :prop_tgt:`CROSSCOMPILING_EMULATOR` target property is set).
In this case, the contents of :prop_tgt:`CROSSCOMPILING_EMULATOR` will be
prepended to the command before the location of the target executable.
If neither of the above conditions are met, it is assumed that the
command name is a program to be found on the ``PATH`` at build time.
Arguments to ``COMMAND`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
Use the :genex:`TARGET_FILE` generator expression to refer to the location
of a target later in the command line (i.e. as a command argument rather
than as the command to execute).
Whenever one of the following target based generator expressions are used as
a command to execute or is mentioned in a command argument, a target-level
dependency will be added automatically so that the mentioned target will be
built before any target using this custom command
(see policy :policy:`CMP0112`).
* ``TARGET_FILE``
* ``TARGET_LINKER_FILE``
* ``TARGET_SONAME_FILE``
* ``TARGET_PDB_FILE``
This target-level dependency does NOT add a file-level dependency that would
cause the custom command to re-run whenever the executable is recompiled.
List target names with the ``DEPENDS`` option to add such file-level
dependencies.
``COMMENT``
Display the given message before the commands are executed at
build time. This will be ignored if ``APPEND`` is given, although a future
version may use it.
.. versionadded:: 3.26
Arguments to ``COMMENT`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``DEPENDS``
Specify files on which the command depends. Each argument is converted
to a dependency as follows:
1. If the argument is the name of a target (created by the
:command:`add_custom_target`, :command:`add_executable`, or
:command:`add_library` command) a target-level dependency is
created to make sure the target is built before any target
using this custom command. Additionally, if the target is an
executable or library, a file-level dependency is created to
cause the custom command to re-run whenever the target is
recompiled.
.. versionchanged:: 4.4
Previously an executable target could be specified using the name
of the target with ``.exe`` appended. This is no longer allowed.
See policy :policy:`CMP0212`.
2. If the argument is an absolute path, a file-level dependency
is created on that path.
3. If the argument is the name of a source file that has been
added to a target or on which a source file property has been set,
a file-level dependency is created on that source file.
4. If the argument is a relative path and it exists in the current
source directory, a file-level dependency is created on that
file in the current source directory.
5. Otherwise, a file-level dependency is created on that path relative
to the current binary directory.
If any dependency is an ``OUTPUT`` of another custom command in the same
directory (``CMakeLists.txt`` file), CMake automatically brings the other
custom command into the target in which this command is built.
.. versionadded:: 3.16
A target-level dependency is added if any dependency is listed as
``BYPRODUCTS`` of a target or any of its build events in the same
directory to ensure the byproducts will be available.
If ``DEPENDS`` is not specified, the command will run whenever
the ``OUTPUT`` is missing; if the command does not actually
create the ``OUTPUT``, the rule will always run.
.. versionadded:: 3.1
Arguments to ``DEPENDS`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``COMMAND_EXPAND_LISTS``
.. versionadded:: 3.8
Lists in ``COMMAND`` arguments will be expanded, including those
created with
:manual:`generator expressions <cmake-generator-expressions(7)>`,
allowing ``COMMAND`` arguments such as
``${CC} "-I$<JOIN:$<TARGET_PROPERTY:foo,INCLUDE_DIRECTORIES>,;-I>" foo.cc``
to be properly expanded.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
If the appended commands need this option to be set, it must be set on the
first call to ``add_custom_command(OUTPUT...)`` for the output files.
``CODEGEN``
.. versionadded:: 3.31
Adds the custom command to a global ``codegen`` target that can be
used to execute the custom command while avoiding the majority of the
build graph.
This option is supported only by :ref:`Ninja Generators` and
:ref:`Makefile Generators`, and is ignored by other generators.
Furthermore, this option is allowed only if policy :policy:`CMP0171`
is set to ``NEW``.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
It can only be set on the first call to ``add_custom_command(OUTPUT...)``
for the output files.
``IMPLICIT_DEPENDS``
Request scanning of implicit dependencies of an input file.
The language given specifies the programming language whose
corresponding dependency scanner should be used.
Currently only ``C`` and ``CXX`` language scanners are supported.
The language has to be specified for every file in the
``IMPLICIT_DEPENDS`` list. Dependencies discovered from the
scanning are added to those of the custom command at build time.
Note that the ``IMPLICIT_DEPENDS`` option is currently supported
only for Makefile generators and will be ignored by other generators.
.. note::
This option cannot be specified at the same time as ``DEPFILE`` option.
``JOB_POOL``
.. versionadded:: 3.15
Specify a :prop_gbl:`pool <JOB_POOLS>` for the :generator:`Ninja`
generator. Incompatible with ``USES_TERMINAL``, which implies
the ``console`` pool.
Using a pool that is not defined by :prop_gbl:`JOB_POOLS` causes
an error by ninja at build time.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
Job pools can only be specified in the first call to
``add_custom_command(OUTPUT...)`` for the output files.
``JOB_SERVER_AWARE``
.. versionadded:: 3.28
Specify that the command is GNU Make job server aware.
For the :generator:`Unix Makefiles`, :generator:`MSYS Makefiles`, and
:generator:`MinGW Makefiles` generators this will add the ``+`` prefix to the
recipe line. See the `GNU Make Documentation`_ for more information.
This option is silently ignored by other generators.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
Job server awareness can only be specified in the first call to
``add_custom_command(OUTPUT...)`` for the output files.
.. _`GNU Make Documentation`: https://www.gnu.org/software/make/manual/html_node/MAKE-Variable.html
``MAIN_DEPENDENCY``
Specify the primary input source file to the command. This is
treated just like any value given to the ``DEPENDS`` option
but also suggests to :ref:`Visual Studio Generators` where to hang
the custom command. Each source file may have at most one command
specifying it as its main dependency. A compile command (i.e. for a
library or an executable) counts as an implicit main dependency which
gets silently overwritten by a custom command specification.
This option is currently ignored if ``APPEND`` is given, but a future
version may use it.
``OUTPUT``
Specify the output files the command is expected to produce.
Each output file will be marked with the :prop_sf:`GENERATED`
source file property automatically.
If the output of the custom command is not actually created
as a file on disk it should be marked with the :prop_sf:`SYMBOLIC`
source file property.
If an output file name is a relative path, its absolute path is
determined by interpreting it relative to:
1. the build directory corresponding to the current source directory
(:variable:`CMAKE_CURRENT_BINARY_DIR`), or
2. the current source directory (:variable:`CMAKE_CURRENT_SOURCE_DIR`).
The path in the build directory is preferred unless the path in the
source tree is mentioned as an absolute source file path elsewhere
in the current directory.
The output file path may not contain ``<`` or ``>`` characters.
.. versionadded:: 3.20
Arguments to ``OUTPUT`` may use a restricted set of
:manual:`generator expressions <cmake-generator-expressions(7)>`.
:ref:`Target-dependent expressions <Target-Dependent Expressions>`
are not permitted.
.. versionchanged:: 3.28
In targets using :ref:`file sets`, custom command outputs are now
considered private unless they are listed in a non-private file set.
See policy :policy:`CMP0154`.
.. versionchanged:: 3.30
The output file path may now use ``#`` characters, except
when using the :generator:`Borland Makefiles` generator.
``USES_TERMINAL``
.. versionadded:: 3.2
The command will be given direct access to the terminal if possible.
With the :generator:`Ninja` generator, this places the command in
the ``console`` :prop_gbl:`pool <JOB_POOLS>`.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
If the appended commands need access to the terminal, it must be set on
the first call to ``add_custom_command(OUTPUT...)`` for the output files.
``VERBATIM``
All arguments to the commands will be escaped properly for the
build tool so that the invoked command receives each argument
unchanged. Note that one level of escapes is still used by the
CMake language processor before add_custom_command even sees the
arguments. Use of ``VERBATIM`` is recommended as it enables
correct behavior. When ``VERBATIM`` is not given the behavior
is platform specific because there is no protection of
tool-specific special characters.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
If the appended commands need to be treated as ``VERBATIM``, it must be set
on the first call to ``add_custom_command(OUTPUT...)`` for the output files.
``WORKING_DIRECTORY``
Execute the command with the given current working directory.
If it is a relative path, it will be interpreted relative to the
build tree directory corresponding to the current source directory.
If not specified, set to :variable:`CMAKE_CURRENT_BINARY_DIR`.
This option is currently ignored if ``APPEND`` is given, but a future
version may use it.
.. versionadded:: 3.13
Arguments to ``WORKING_DIRECTORY`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``DEPFILE``
.. versionadded:: 3.7
Specify a depfile which holds dependencies for the custom command. It is
usually emitted by the custom command itself. This keyword may only be used
if the generator supports it, as detailed below.
The expected format, compatible with what is generated by ``gcc`` with the
option ``-M``, is independent of the generator or platform.
The formal syntax, as specified using
`BNF <https://en.wikipedia.org/wiki/Backus%E2%80%93Naur_form>`_ notation with
the regular extensions, is the following:
.. raw:: latex
\begin{small}
.. productionlist:: depfile
depfile: `rule`*
rule: `targets` (':' (`separator` `dependencies`?)?)? `eol`
targets: `target` (`separator` `target`)* `separator`*
target: `pathname`
dependencies: `dependency` (`separator` `dependency`)* `separator`*
dependency: `pathname`
separator: (`space` | `line_continue`)+
line_continue: '\' `eol`
space: ' ' | '\t'
pathname: `character`+
character: `std_character` | `dollar` | `hash` | `whitespace`
std_character: <any character except '$', '#' or ' '>
dollar: '$$'
hash: '\#'
whitespace: '\ '
eol: '\r'? '\n'
.. raw:: latex
\end{small}
.. note::
As part of ``pathname``, any slash and backslash is interpreted as
a directory separator.
.. versionadded:: 3.7
The :generator:`Ninja` generator supports ``DEPFILE`` since the keyword
was first added.
.. versionadded:: 3.17
Added the :generator:`Ninja Multi-Config` generator, which included
support for the ``DEPFILE`` keyword.
.. versionadded:: 3.20
Added support for :ref:`Makefile Generators`.
.. note::
``DEPFILE`` cannot be specified at the same time as the
``IMPLICIT_DEPENDS`` option for :ref:`Makefile Generators`.
.. versionadded:: 3.21
Added support for :ref:`Visual Studio Generators` with VS 2012 and above,
and for the :generator:`Xcode` generator. Support for
:manual:`generator expressions <cmake-generator-expressions(7)>` was also
added.
.. versionadded:: 3.29
The :ref:`Ninja Generators` will now incorporate the dependencies into its
"deps log" database if the file is not listed in ``OUTPUTS`` or
``BYPRODUCTS``.
Using ``DEPFILE`` with generators other than those listed above is an error.
If the ``DEPFILE`` argument is relative, it should be relative to
:variable:`CMAKE_CURRENT_BINARY_DIR`, and any relative paths inside the
``DEPFILE`` should also be relative to :variable:`CMAKE_CURRENT_BINARY_DIR`.
See policy :policy:`CMP0116`, which is always ``NEW`` for
:ref:`Makefile Generators`, :ref:`Visual Studio Generators`,
and the :generator:`Xcode` generator.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
Depfiles can only be set on the first call to
``add_custom_command(OUTPUT...)`` for the output files.
``DEPENDS_EXPLICIT_ONLY``
.. versionadded:: 3.27
Indicates that the command's ``DEPENDS`` argument represents all files
required by the command and implicit dependencies are not required.
Without this option, if any target uses the output of the custom command,
CMake will consider that target's dependencies as implicit dependencies for
the custom command in case this custom command requires files implicitly
created by those targets.
This option can be enabled on all custom commands by setting
:variable:`CMAKE_ADD_CUSTOM_COMMAND_DEPENDS_EXPLICIT_ONLY` to ``ON``.
This keyword cannot be used with ``APPEND`` (see policy :policy:`CMP0175`).
It can only be set on the first call to ``add_custom_command(OUTPUT...)``
for the output files.
Only the :ref:`Ninja Generators` actually use this information to remove
unnecessary implicit dependencies.
See also the :prop_tgt:`OPTIMIZE_DEPENDENCIES` target property, which may
provide another way for reducing the impact of target dependencies in some
scenarios.
Examples: Generating Files
^^^^^^^^^^^^^^^^^^^^^^^^^^
Custom commands may be used to generate source files.
For example, the code:
.. code-block:: cmake
add_custom_command(
OUTPUT out.c
COMMAND someTool -i ${CMAKE_CURRENT_SOURCE_DIR}/in.txt
-o out.c
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/in.txt
VERBATIM)
add_library(myLib out.c)
adds a custom command to run ``someTool`` to generate ``out.c`` and then
compile the generated source as part of a library. The generation rule
will re-run whenever ``in.txt`` changes.
.. versionadded:: 3.20
One may use generator expressions to specify per-configuration outputs.
For example, the code:
.. code-block:: cmake
add_custom_command(
OUTPUT "out-$<CONFIG>.c"
COMMAND someTool -i ${CMAKE_CURRENT_SOURCE_DIR}/in.txt
-o "out-$<CONFIG>.c"
-c "$<CONFIG>"
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/in.txt
VERBATIM)
add_library(myLib "out-$<CONFIG>.c")
adds a custom command to run ``someTool`` to generate ``out-<config>.c``,
where ``<config>`` is the build configuration, and then compile the generated
source as part of a library.
.. versionadded:: 3.31
Use the ``CODEGEN`` option to add a custom command's outputs to the builtin
``codegen`` target. This is useful to make generated code available for
static analysis without building the entire project. For example:
.. code-block:: cmake
add_executable(someTool someTool.c)
add_custom_command(
OUTPUT out.c
COMMAND someTool -o out.c
CODEGEN)
add_library(myLib out.c)
A user may build the ``codegen`` target to generate ``out.c``.
``someTool`` is built as dependency, but ``myLib`` is not built at all.
Example: Generating Files for Multiple Targets
""""""""""""""""""""""""""""""""""""""""""""""
If multiple independent targets need the same custom command output,
it must be attached to a single custom target on which they all depend.
Consider the following example:
.. code-block:: cmake
add_custom_command(
OUTPUT table.csv
COMMAND makeTable -i ${CMAKE_CURRENT_SOURCE_DIR}/input.dat
-o table.csv
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/input.dat
VERBATIM)
add_custom_target(generate_table_csv DEPENDS table.csv)
add_custom_command(
OUTPUT foo.cxx
COMMAND genFromTable -i table.csv -case foo -o foo.cxx
DEPENDS table.csv # file-level dependency
generate_table_csv # target-level dependency
VERBATIM)
add_library(foo foo.cxx)
add_custom_command(
OUTPUT bar.cxx
COMMAND genFromTable -i table.csv -case bar -o bar.cxx
DEPENDS table.csv # file-level dependency
generate_table_csv # target-level dependency
VERBATIM)
add_library(bar bar.cxx)
Output ``foo.cxx`` is needed only by target ``foo`` and output ``bar.cxx``
is needed only by target ``bar``, but *both* targets need ``table.csv``,
transitively. Since ``foo`` and ``bar`` are independent targets that may
build concurrently, we prevent them from racing to generate ``table.csv``
by placing its custom command in a separate target, ``generate_table_csv``.
The custom commands generating ``foo.cxx`` and ``bar.cxx`` each specify a
target-level dependency on ``generate_table_csv``, so the targets using them,
``foo`` and ``bar``, will not build until after target ``generate_table_csv``
is built.
Build Events
^^^^^^^^^^^^
.. signature::
add_custom_command(TARGET <target>
PRE_BUILD | PRE_LINK | POST_BUILD
[...])
Add a build event to a target such as a
library or executable. This is useful for performing an operation
before or after building the target. The command becomes part of the
target and will only execute when the target itself is built. If the
target is already built, the command will not execute.
.. code-block:: cmake
add_custom_command(TARGET <target>
PRE_BUILD | PRE_LINK | POST_BUILD
COMMAND <command1> [ARGS] [<args1>...]
[COMMAND <command2> [ARGS] [<args2>...]] ...
[BYPRODUCTS <files>...]
[WORKING_DIRECTORY <dir>]
[COMMENT <comment>]
[VERBATIM]
[COMMAND_EXPAND_LISTS]
[USES_TERMINAL])
This defines a new command that will be associated with building the
specified ``<target>``. The ``<target>`` must be defined in the current
directory; targets defined in other directories may not be specified.
When the command will happen is determined by which
of the following is specified:
``PRE_BUILD``
This option has unique behavior for the :ref:`Visual Studio Generators`.
When using one of the Visual Studio generators, the command will run before
any other rules are executed within the target. With all other generators,
this option behaves the same as ``PRE_LINK`` instead. Because of this,
it is recommended to avoid using ``PRE_BUILD`` except when it is known that
a Visual Studio generator is being used.
``PRE_LINK``
Run after sources have been compiled but before linking the binary
or running the librarian or archiver tool of a static library.
This is not defined for targets created by the
:command:`add_custom_target` command.
``POST_BUILD``
Run after all other rules within the target have been executed.
Projects should always specify one of the above three keywords when using
the ``TARGET`` form. See policy :policy:`CMP0175`.
All other keywords shown in the signature above have the same meaning as they
do for the :command:`add_custom_command(OUTPUT)` form of the command.
At least one ``COMMAND`` must be given, see policy :policy:`CMP0175`.
.. note::
Because generator expressions can be used in custom commands,
it is possible to define ``COMMAND`` lines or whole custom commands
which evaluate to empty strings for certain configurations.
For :ref:`Visual Studio Generators` these command
lines or custom commands will be omitted for the specific
configuration and no "empty-string-command" will be added.
This allows adding individual build events for every configuration.
.. versionadded:: 3.21
Support for target-dependent generator expressions.
.. versionadded:: 3.29
The ``<target>`` may be an :ref:`ALIAS target <Alias Targets>`.
Examples: Build Events
^^^^^^^^^^^^^^^^^^^^^^
A ``POST_BUILD`` event may be used to post-process a binary after linking.
For example, the code:
.. code-block:: cmake
add_executable(myExe myExe.c)
add_custom_command(
TARGET myExe POST_BUILD
COMMAND someHasher -i "$<TARGET_FILE:myExe>"
-o "$<TARGET_FILE:myExe>.hash"
VERBATIM)
will run ``someHasher`` to produce a ``.hash`` file next to the executable
after linking.
.. versionadded:: 3.20
One may use generator expressions to specify per-configuration byproducts.
For example, the code:
.. code-block:: cmake
add_library(myPlugin MODULE myPlugin.c)
add_custom_command(
TARGET myPlugin POST_BUILD
COMMAND someHasher -i "$<TARGET_FILE:myPlugin>"
--as-code "myPlugin-hash-$<CONFIG>.c"
BYPRODUCTS "myPlugin-hash-$<CONFIG>.c"
VERBATIM)
add_executable(myExe myExe.c "myPlugin-hash-$<CONFIG>.c")
will run ``someHasher`` after linking ``myPlugin``, e.g. to produce a ``.c``
file containing code to check the hash of ``myPlugin`` that the ``myExe``
executable can use to verify it before loading.
Ninja Multi-Config
^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.20
``add_custom_command`` supports the :generator:`Ninja Multi-Config`
generator's cross-config capabilities. See the generator documentation
for more information.
See Also
^^^^^^^^
* :command:`add_custom_target`
@@ -0,0 +1,212 @@
add_custom_target
-----------------
Add a target with no output so it will always be built.
.. code-block:: cmake
add_custom_target(Name [ALL] [command1 [<args1>...]]
[COMMAND command2 [<args2>...]] ...
[DEPENDS <depend>...]
[BYPRODUCTS <file>...]
[WORKING_DIRECTORY <dir>]
[COMMENT <comment>]
[JOB_POOL <job_pool>]
[JOB_SERVER_AWARE <bool>]
[VERBATIM] [USES_TERMINAL]
[COMMAND_EXPAND_LISTS]
[SOURCES <source>...])
Adds a target with the given name that executes the given commands.
The target has no output file and is *always considered out of date*
even if the commands try to create a file with the name of the target.
Use the :command:`add_custom_command` command to generate a file with
dependencies. By default nothing depends on the custom target. Use
the :command:`add_dependencies` command to add dependencies to or
from other targets.
The options are:
``ALL``
Indicate that this target should be added to the default build
target so that it will be run every time (the command cannot be
called ``ALL``).
``BYPRODUCTS``
.. versionadded:: 3.2
Specify the files the command is expected to produce but whose
modification time may or may not be updated on subsequent builds.
If a byproduct name is a relative path it will be interpreted
relative to the build tree directory corresponding to the
current source directory.
Each byproduct file will be marked with the :prop_sf:`GENERATED`
source file property automatically.
*See policy* :policy:`CMP0058` *for the motivation behind this feature.*
Explicit specification of byproducts is supported by the
:generator:`Ninja` generator to tell the ``ninja`` build tool
how to regenerate byproducts when they are missing. It is
also useful when other build rules (e.g. custom commands)
depend on the byproducts. Ninja requires a build rule for any
generated file on which another rule depends even if there are
order-only dependencies to ensure the byproducts will be
available before their dependents build.
The :ref:`Makefile Generators` will remove ``BYPRODUCTS`` and other
:prop_sf:`GENERATED` files during ``make clean``.
.. versionadded:: 3.20
Arguments to ``BYPRODUCTS`` may use a restricted set of
:manual:`generator expressions <cmake-generator-expressions(7)>`.
:ref:`Target-dependent expressions <Target-Dependent Expressions>`
are not permitted.
.. versionchanged:: 3.28
In custom targets using :ref:`file sets`, byproducts are now
considered private unless they are listed in a non-private file set.
See policy :policy:`CMP0154`.
``COMMAND``
Specify the command-line(s) to execute at build time.
If more than one ``COMMAND`` is specified they will be executed in order,
but *not* necessarily composed into a stateful shell or batch script.
(To run a full script, use the :command:`configure_file` command or the
:command:`file(GENERATE)` command to create it, and then specify
a ``COMMAND`` to launch it.)
If ``COMMAND`` specifies an executable target name (created by the
:command:`add_executable` command), it will automatically be replaced
by the location of the executable created at build time if either of
the following is true:
* The target is not being cross-compiled (i.e. the
:variable:`CMAKE_CROSSCOMPILING` variable is not set to true).
* .. versionadded:: 3.6
The target is being cross-compiled and an emulator is provided (i.e.
its :prop_tgt:`CROSSCOMPILING_EMULATOR` target property is set).
In this case, the contents of :prop_tgt:`CROSSCOMPILING_EMULATOR` will be
prepended to the command before the location of the target executable.
If neither of the above conditions are met, it is assumed that the
command name is a program to be found on the ``PATH`` at build time.
Arguments to ``COMMAND`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
Use the :genex:`TARGET_FILE` generator expression to refer to the location
of a target later in the command line (i.e. as a command argument rather
than as the command to execute).
Whenever one of the following target based generator expressions are used as
a command to execute or is mentioned in a command argument, a target-level
dependency will be added automatically so that the mentioned target will be
built before this custom target (see policy :policy:`CMP0112`).
* ``TARGET_FILE``
* ``TARGET_LINKER_FILE``
* ``TARGET_SONAME_FILE``
* ``TARGET_PDB_FILE``
The command and arguments are optional and if not specified an empty
target will be created.
``COMMENT``
Display the given message before the commands are executed at
build time.
.. versionadded:: 3.26
Arguments to ``COMMENT`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``DEPENDS``
Reference files and outputs of custom commands created with
:command:`add_custom_command` command calls in the same directory
(``CMakeLists.txt`` file). They will be brought up to date when
the target is built.
.. versionchanged:: 3.16
A target-level dependency is added if any dependency is a byproduct
of a target or any of its build events in the same directory to ensure
the byproducts will be available before this target is built.
Use the :command:`add_dependencies` command to add dependencies
on other targets.
``COMMAND_EXPAND_LISTS``
.. versionadded:: 3.8
Lists in ``COMMAND`` arguments will be expanded, including those
created with
:manual:`generator expressions <cmake-generator-expressions(7)>`,
allowing ``COMMAND`` arguments such as
``${CC} "-I$<JOIN:$<TARGET_PROPERTY:foo,INCLUDE_DIRECTORIES>,;-I>" foo.cc``
to be properly expanded.
``JOB_POOL``
.. versionadded:: 3.15
Specify a :prop_gbl:`pool <JOB_POOLS>` for the :generator:`Ninja`
generator. Incompatible with ``USES_TERMINAL``, which implies
the ``console`` pool.
Using a pool that is not defined by :prop_gbl:`JOB_POOLS` causes
an error by ninja at build time.
``JOB_SERVER_AWARE``
.. versionadded:: 3.28
Specify that the command is GNU Make job server aware.
For the :generator:`Unix Makefiles`, :generator:`MSYS Makefiles`, and
:generator:`MinGW Makefiles` generators this will add the ``+`` prefix to the
recipe line. See the `GNU Make Documentation`_ for more information.
This option is silently ignored by other generators.
.. _`GNU Make Documentation`: https://www.gnu.org/software/make/manual/html_node/MAKE-Variable.html
``SOURCES``
Specify additional source files to be included in the custom target.
Specified source files will be added to IDE project files for
convenience in editing even if they have no build rules.
``VERBATIM``
All arguments to the commands will be escaped properly for the
build tool so that the invoked command receives each argument
unchanged. Note that one level of escapes is still used by the
CMake language processor before ``add_custom_target`` even sees
the arguments. Use of ``VERBATIM`` is recommended as it enables
correct behavior. When ``VERBATIM`` is not given the behavior
is platform specific because there is no protection of
tool-specific special characters.
``USES_TERMINAL``
.. versionadded:: 3.2
The command will be given direct access to the terminal if possible.
With the :generator:`Ninja` generator, this places the command in
the ``console`` :prop_gbl:`pool <JOB_POOLS>`.
``WORKING_DIRECTORY``
Execute the command with the given current working directory.
If it is a relative path it will be interpreted relative to the
build tree directory corresponding to the current source directory.
If not specified, set to :variable:`CMAKE_CURRENT_BINARY_DIR`.
.. versionadded:: 3.13
Arguments to ``WORKING_DIRECTORY`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
Ninja Multi-Config
^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.20
``add_custom_target`` supports the :generator:`Ninja Multi-Config`
generator's cross-config capabilities. See the generator documentation
for more information.
See Also
^^^^^^^^
* :command:`add_custom_command`
@@ -0,0 +1,38 @@
add_definitions
---------------
Add ``-D`` define flags to the compilation of source files.
.. code-block:: cmake
add_definitions(-DFOO -DBAR ...)
Adds definitions to the compiler command line for targets in the current
directory, whether added before or after this command is invoked, and for
the ones in sub-directories added after. This command can be used to add any
flags, but it is intended to add preprocessor definitions.
.. note::
This command has been superseded by alternatives:
* Use :command:`add_compile_definitions` to add preprocessor definitions.
* Use :command:`include_directories` to add include directories.
* Use :command:`add_compile_options` to add other options.
Flags beginning in ``-D`` or ``/D`` that look like preprocessor definitions are
automatically added to the :prop_dir:`COMPILE_DEFINITIONS` directory
property for the current directory. Definitions with non-trivial values
may be left in the set of flags instead of being converted for reasons of
backwards compatibility. See documentation of the
:prop_dir:`directory <COMPILE_DEFINITIONS>`,
:prop_tgt:`target <COMPILE_DEFINITIONS>`,
:prop_sf:`source file <COMPILE_DEFINITIONS>` ``COMPILE_DEFINITIONS``
properties for details on adding preprocessor definitions to specific
scopes and configurations.
See Also
^^^^^^^^
* The :manual:`cmake-buildsystem(7)` manual for more on defining
buildsystem properties.
@@ -0,0 +1,46 @@
add_dependencies
----------------
Add a dependency between top-level targets.
.. code-block:: cmake
add_dependencies(<target> <target-dependency>...)
Makes a top-level ``<target>`` depend on other top-level targets to
ensure that they build before ``<target>`` does. A top-level target
is one created by one of the :command:`add_executable`,
:command:`add_library`, or :command:`add_custom_target` commands
(but not targets generated by CMake like ``install``).
Dependencies added to an :ref:`imported target <Imported Targets>`
or an :ref:`interface library <Interface Libraries>` are followed
transitively in its place since the target itself does not build.
.. versionadded:: 3.3
Allow adding dependencies to interface libraries.
.. versionadded:: 3.8
Dependencies will populate the :prop_tgt:`MANUALLY_ADDED_DEPENDENCIES`
property of ``<target>``.
.. versionchanged:: 3.9
The :ref:`Ninja Generators` use weaker ordering than
other generators in order to improve available concurrency.
They only guarantee that the dependencies' custom commands are
finished before sources in ``<target>`` start compiling; this
ensures generated sources are available.
.. versionchanged:: 4.1
The command may be called with no dependencies.
Previously, at least one dependency was required.
See Also
^^^^^^^^
* The ``DEPENDS`` option of :command:`add_custom_target` and
:command:`add_custom_command` commands for adding file-level
dependencies in custom rules.
* The :prop_sf:`OBJECT_DEPENDS` source file property to add
file-level dependencies to object files.
@@ -0,0 +1,123 @@
add_executable
--------------
.. only:: html
.. contents::
Add an executable to the project using the specified source files.
Normal Executables
^^^^^^^^^^^^^^^^^^
.. signature::
add_executable(<name> <options>... <sources>...)
:target: normal
Add an :ref:`executable <Executables>` target called ``<name>`` to
be built from the source files listed in the command invocation.
The options are:
``WIN32``
Set the :prop_tgt:`WIN32_EXECUTABLE` target property automatically.
See documentation of that target property for details.
``MACOSX_BUNDLE``
Set the :prop_tgt:`MACOSX_BUNDLE` target property automatically.
See documentation of that target property for details.
``EXCLUDE_FROM_ALL``
Set the :prop_tgt:`EXCLUDE_FROM_ALL` target property automatically.
See documentation of that target property for details.
The ``<name>`` corresponds to the logical target name and must be globally
unique within a project. The actual file name of the executable built is
constructed based on conventions of the native platform (such as
``<name>.exe`` or just ``<name>``).
.. versionadded:: 3.1
Source arguments to ``add_executable`` may use "generator expressions" with
the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
manual for available expressions.
.. versionadded:: 3.11
The source files can be omitted if they are added later using
:command:`target_sources`.
By default the executable file will be created in the build tree
directory corresponding to the source tree directory in which the
command was invoked. See documentation of the
:prop_tgt:`RUNTIME_OUTPUT_DIRECTORY` target property to change this
location. See documentation of the :prop_tgt:`OUTPUT_NAME` target property
to change the ``<name>`` part of the final file name.
See the :manual:`cmake-buildsystem(7)` manual for more on defining
buildsystem properties.
See also :prop_sf:`HEADER_FILE_ONLY` on what to do if some sources are
pre-processed, and you want to have the original sources reachable from
within IDE.
Imported Executables
^^^^^^^^^^^^^^^^^^^^
.. signature::
add_executable(<name> IMPORTED [GLOBAL])
:target: IMPORTED
Add an :ref:`IMPORTED executable target <Imported Targets>` to reference
an executable file located outside the project. The target name may be
referenced like any target built within the project, except that by
default it is visible only in the directory in which it is created,
and below.
The options are:
``GLOBAL``
Make the target name globally visible.
No rules are generated to build imported targets, and the :prop_tgt:`IMPORTED`
target property is ``True``. Imported executables are useful for convenient
reference from commands like :command:`add_custom_command`.
Details about the imported executable are specified by setting properties
whose names begin in ``IMPORTED_``. The most important such property is
:prop_tgt:`IMPORTED_LOCATION` (and its per-configuration version
:prop_tgt:`IMPORTED_LOCATION_<CONFIG>`) which specifies the location of
the main executable file on disk. See documentation of the ``IMPORTED_*``
properties for more information.
Alias Executables
^^^^^^^^^^^^^^^^^
.. signature::
add_executable(<name> ALIAS <target>)
:target: ALIAS
Creates an :ref:`Alias Target <Alias Targets>`, such that ``<name>`` can
be used to refer to ``<target>`` in subsequent commands. The ``<name>``
does not appear in the generated buildsystem as a make target. The
``<target>`` may not be an ``ALIAS``.
.. versionadded:: 3.11
An ``ALIAS`` can target a ``GLOBAL`` :ref:`Imported Target <Imported Targets>`
.. versionadded:: 3.18
An ``ALIAS`` can target a non-``GLOBAL`` Imported Target. Such alias is
scoped to the directory in which it is created and subdirectories.
The :prop_tgt:`ALIAS_GLOBAL` target property can be used to check if the
alias is global or not.
``ALIAS`` targets can be used as targets to read properties
from, executables for custom commands and custom targets. They can also be
tested for existence with the regular :command:`if(TARGET)` subcommand.
The ``<name>`` may not be used to modify properties of ``<target>``, that
is, it may not be used as the operand of :command:`set_property`,
:command:`set_target_properties`, :command:`target_link_libraries` etc.
An ``ALIAS`` target may not be installed or exported.
See Also
^^^^^^^^
* :command:`add_library`
@@ -0,0 +1,329 @@
add_library
-----------
.. only:: html
.. contents::
Add a library to the project using the specified source files.
Normal Libraries
^^^^^^^^^^^^^^^^
.. signature::
add_library(<name> [<type>] [EXCLUDE_FROM_ALL] <sources>...)
:target: normal
Add a library target called ``<name>`` to be built from the source files
listed in the command invocation.
The optional ``<type>`` specifies the type of library to be created:
``STATIC``
A :ref:`Static Library <Static Libraries>`:
an archive of object files for use when linking other targets.
``SHARED``
A :ref:`Shared Library <Shared Libraries>`:
a dynamic library that may be linked by other targets and loaded
at runtime.
``MODULE``
A :ref:`Module Library <Module Libraries>`:
a plugin that may not be linked by other targets, but may be
dynamically loaded at runtime using dlopen-like functionality.
If no ``<type>`` is given the default is ``STATIC`` or ``SHARED``
based on the value of the :variable:`BUILD_SHARED_LIBS` variable.
The options are:
``EXCLUDE_FROM_ALL``
Set the :prop_tgt:`EXCLUDE_FROM_ALL` target property automatically.
See documentation of that target property for details.
The ``<name>`` corresponds to the logical target name and must be globally
unique within a project. The actual file name of the library built is
constructed based on conventions of the native platform (such as
``lib<name>.a`` or ``<name>.lib``).
.. versionadded:: 3.1
Source arguments to ``add_library`` may use "generator expressions" with
the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
manual for available expressions.
.. versionadded:: 3.11
The source files can be omitted if they are added later using
:command:`target_sources`.
For ``SHARED`` and ``MODULE`` libraries the
:prop_tgt:`POSITION_INDEPENDENT_CODE` target
property is set to ``ON`` automatically.
A ``SHARED`` library may be marked with the :prop_tgt:`FRAMEWORK`
target property to create an macOS Framework.
.. versionadded:: 3.8
A ``STATIC`` library may be marked with the :prop_tgt:`FRAMEWORK`
target property to create a static Framework.
If a library does not export any symbols, it must not be declared as a
``SHARED`` library. For example, a Windows resource DLL or a managed C++/CLI
DLL that exports no unmanaged symbols would need to be a ``MODULE`` library.
This is because CMake expects a ``SHARED`` library to always have an
associated import library on Windows.
By default the library file will be created in the build tree directory
corresponding to the source tree directory in which the command was
invoked. See documentation of the :prop_tgt:`ARCHIVE_OUTPUT_DIRECTORY`,
:prop_tgt:`LIBRARY_OUTPUT_DIRECTORY`, and
:prop_tgt:`RUNTIME_OUTPUT_DIRECTORY` target properties to change this
location. See documentation of the :prop_tgt:`OUTPUT_NAME` target
property to change the ``<name>`` part of the final file name.
See the :manual:`cmake-buildsystem(7)` manual for more on defining
buildsystem properties.
See also :prop_sf:`HEADER_FILE_ONLY` on what to do if some sources are
pre-processed, and you want to have the original sources reachable from
within IDE.
.. versionchanged:: 3.30
On platforms that do not support shared libraries, ``add_library``
now fails on calls creating ``SHARED`` libraries instead of
automatically converting them to ``STATIC`` libraries as before.
See policy :policy:`CMP0164`.
Object Libraries
^^^^^^^^^^^^^^^^
.. signature::
add_library(<name> OBJECT <sources>...)
:target: OBJECT
Add an :ref:`Object Library <Object Libraries>` to compile source files
without archiving or linking their object files into a library.
Other targets created by ``add_library`` or :command:`add_executable`
may reference the objects using an expression of the
form :genex:`$\<TARGET_OBJECTS:objlib\> <TARGET_OBJECTS>` as a source, where
``objlib`` is the object library name. For example:
.. code-block:: cmake
add_library(... $<TARGET_OBJECTS:objlib> ...)
add_executable(... $<TARGET_OBJECTS:objlib> ...)
will include objlib's object files in a library and an executable
along with those compiled from their own sources. Object libraries
may contain only sources that compile, header files, and other files
that would not affect linking of a normal library (e.g. ``.txt``).
They may contain custom commands generating such sources, but not
``PRE_BUILD``, ``PRE_LINK``, or ``POST_BUILD`` commands. Some native build
systems (such as :generator:`Xcode`) may not like targets that have only
object files, so consider adding at least one real source file to any target
that references :genex:`$\<TARGET_OBJECTS:objlib\> <TARGET_OBJECTS>`.
.. versionadded:: 3.12
Object libraries can be linked to with :command:`target_link_libraries`.
Interface Libraries
^^^^^^^^^^^^^^^^^^^
.. signature::
add_library(<name> INTERFACE)
:target: INTERFACE
Add an :ref:`Interface Library <Interface Libraries>` target that may
specify usage requirements for dependents but does not compile sources
and does not produce a library artifact on disk.
An interface library with no source files is not included as a target
in the generated buildsystem. However, it may have
properties set on it and it may be installed and exported.
Typically, ``INTERFACE_*`` properties are populated on an interface
target using the commands:
* :command:`set_property`,
* :command:`target_link_libraries(INTERFACE)`,
* :command:`target_link_options(INTERFACE)`,
* :command:`target_include_directories(INTERFACE)`,
* :command:`target_compile_options(INTERFACE)`,
* :command:`target_compile_definitions(INTERFACE)`, and
* :command:`target_sources(INTERFACE)`,
and then it is used as an argument to :command:`target_link_libraries`
like any other target.
.. versionadded:: 3.15
An interface library can have :prop_tgt:`PUBLIC_HEADER` and
:prop_tgt:`PRIVATE_HEADER` properties. The headers specified by those
properties can be installed using the :command:`install(TARGETS)` command.
.. signature::
add_library(<name> INTERFACE [EXCLUDE_FROM_ALL] <sources>...)
:target: INTERFACE-with-sources
.. versionadded:: 3.19
Add an :ref:`Interface Library <Interface Libraries>` target with
source files (in addition to usage requirements and properties as
documented by the :command:`above signature <add_library(INTERFACE)>`).
Source files may be listed directly in the ``add_library`` call
or added later by calls to :command:`target_sources` with the
``PRIVATE`` or ``PUBLIC`` keywords.
If an interface library has source files (i.e. the :prop_tgt:`SOURCES`
target property is set), or header sets (i.e. the :prop_tgt:`HEADER_SETS`
target property is set), it will appear in the generated buildsystem
as a build target much like a target defined by the
:command:`add_custom_target` command. It does not compile any sources,
but does contain build rules for custom commands created by the
:command:`add_custom_command` command.
The options are:
``EXCLUDE_FROM_ALL``
Set the :prop_tgt:`EXCLUDE_FROM_ALL` target property automatically.
See documentation of that target property for details.
.. note::
In most command signatures where the ``INTERFACE`` keyword appears,
the items listed after it only become part of that target's usage
requirements and are not part of the target's own settings. However,
in this signature of ``add_library``, the ``INTERFACE`` keyword refers
to the library type only. Sources listed after it in the ``add_library``
call are ``PRIVATE`` to the interface library and do not appear in its
:prop_tgt:`INTERFACE_SOURCES` target property.
.. signature::
add_library(<name> INTERFACE SYMBOLIC)
:target: INTERFACE-SYMBOLIC
.. versionadded:: 4.2
Add a symbolic :ref:`Interface Library <Interface Libraries>` target.
Symbolic interface libraries are useful for representing optional components
or features in a package. They have no usage requirements, do not compile
sources, and do not produce a library artifact on disk, but they may be
exported and installed. They can also be tested for existence with the
regular :command:`if(TARGET)` subcommand.
A symbolic interface library may be used as a linkable target to enforce the
presence of optional components in a dependency. For example, if a library
``libgui`` may or may not provide a feature ``widget``, a consumer package
can link against ``widget`` to express that it requires this component to be
available. This allows :command:`find_package` calls that declare required
components to be validated by linking against the corresponding symbolic
targets.
A symbolic interface library has the :prop_tgt:`SYMBOLIC` target property
set to true.
.. _`add_library imported libraries`:
Imported Libraries
^^^^^^^^^^^^^^^^^^
.. signature::
add_library(<name> <type> IMPORTED [GLOBAL])
:target: IMPORTED
Add an :ref:`IMPORTED library target <Imported Targets>` called ``<name>``.
The target name may be referenced like any target built within the project,
except that by default it is visible only in the directory in which it is
created, and below.
The ``<type>`` must be one of:
``STATIC``, ``SHARED``, ``MODULE``, ``UNKNOWN``
References a library file located outside the project. The
:prop_tgt:`IMPORTED_LOCATION` target property (or its per-configuration
variant :prop_tgt:`IMPORTED_LOCATION_<CONFIG>`) specifies the
location of the main library file on disk:
* For a ``SHARED`` library on most non-Windows platforms, the main library
file is the ``.so`` or ``.dylib`` file used by both linkers and dynamic
loaders. If the referenced library file has a ``SONAME`` (or on macOS,
has a ``LC_ID_DYLIB`` starting in ``@rpath/``), the value of that field
should be set in the :prop_tgt:`IMPORTED_SONAME` target property.
If the referenced library file does not have a ``SONAME``, but the
platform supports it, then the :prop_tgt:`IMPORTED_NO_SONAME` target
property should be set.
* For a ``SHARED`` library on Windows, the :prop_tgt:`IMPORTED_IMPLIB`
target property (or its per-configuration variant
:prop_tgt:`IMPORTED_IMPLIB_<CONFIG>`) specifies the location of the
DLL import library file (``.lib`` or ``.dll.a``) on disk, and the
``IMPORTED_LOCATION`` is the location of the ``.dll`` runtime
library (and is optional, but needed by the :genex:`TARGET_RUNTIME_DLLS`
generator expression).
Additional usage requirements may be specified in ``INTERFACE_*``
properties.
An ``UNKNOWN`` library type is typically only used in the implementation
of :ref:`Find Modules`. It allows the path to an imported library
(often found using the :command:`find_library` command) to be used
without having to know what type of library it is. This is especially
useful on Windows where a static library and a DLL's import library
both have the same file extension.
``OBJECT``
References a set of object files located outside the project.
The :prop_tgt:`IMPORTED_OBJECTS` target property (or its per-configuration
variant :prop_tgt:`IMPORTED_OBJECTS_<CONFIG>`) specifies the locations of
object files on disk.
Additional usage requirements may be specified in ``INTERFACE_*``
properties.
``INTERFACE``
Does not reference any library or object files on disk, but may
specify usage requirements in ``INTERFACE_*`` properties.
The options are:
``GLOBAL``
Make the target name globally visible.
No rules are generated to build imported targets, and the :prop_tgt:`IMPORTED`
target property is ``True``. Imported libraries are useful for convenient
reference from commands like :command:`target_link_libraries`.
Details about the imported library are specified by setting properties whose
names begin in ``IMPORTED_`` and ``INTERFACE_``. See documentation of
such properties for more information.
Alias Libraries
^^^^^^^^^^^^^^^
.. signature::
add_library(<name> ALIAS <target>)
:target: ALIAS
Creates an :ref:`Alias Target <Alias Targets>`, such that ``<name>`` can be
used to refer to ``<target>`` in subsequent commands. The ``<name>`` does
not appear in the generated buildsystem as a make target. The ``<target>``
may not be an ``ALIAS``.
.. versionadded:: 3.11
An ``ALIAS`` can target a ``GLOBAL`` :ref:`Imported Target <Imported Targets>`
.. versionadded:: 3.18
An ``ALIAS`` can target a non-``GLOBAL`` Imported Target. Such alias is
scoped to the directory in which it is created and below.
The :prop_tgt:`ALIAS_GLOBAL` target property can be used to check if the
alias is global or not.
``ALIAS`` targets can be used as linkable targets and as targets to
read properties from. They can also be tested for existence with the
regular :command:`if(TARGET)` subcommand. The ``<name>`` may not be used
to modify properties of ``<target>``, that is, it may not be used as the
operand of :command:`set_property`, :command:`set_target_properties`,
:command:`target_link_libraries` etc. An ``ALIAS`` target may not be
installed or exported.
See Also
^^^^^^^^
* :command:`add_executable`
@@ -0,0 +1,49 @@
add_link_options
----------------
.. versionadded:: 3.13
Add options to the link step for executable, shared library or module
library targets in the current directory and below that are added after
this command is invoked.
.. code-block:: cmake
add_link_options(<option> ...)
This command can be used to add any link options, but alternative commands
exist to add libraries (:command:`target_link_libraries` or
:command:`link_libraries`). See documentation of the
:prop_dir:`directory <LINK_OPTIONS>` and
:prop_tgt:`target <LINK_OPTIONS>` ``LINK_OPTIONS`` properties.
.. note::
This command cannot be used to add options for static library targets,
since they do not use a linker. To add archiver or MSVC librarian flags,
see the :prop_tgt:`STATIC_LIBRARY_OPTIONS` target property.
.. |command_name| replace:: ``add_link_options``
.. include:: include/GENEX_NOTE.rst
.. include:: include/DEVICE_LINK_OPTIONS.rst
.. include:: include/OPTIONS_SHELL.rst
.. include:: include/LINK_OPTIONS_LINKER.rst
See Also
^^^^^^^^
* :command:`link_libraries`
* :command:`target_link_libraries`
* :command:`target_link_options`
* :variable:`CMAKE_<LANG>_FLAGS` and :variable:`CMAKE_<LANG>_FLAGS_<CONFIG>`
add language-wide flags passed to all invocations of the compiler.
This includes invocations that drive compiling and those that drive linking.
* .. versionadded:: 4.3
:variable:`CMAKE_<LANG>_LINK_FLAGS` and
:variable:`CMAKE_<LANG>_LINK_FLAGS_<CONFIG>` add language-wide flags passed
to all invocations of the compiler which drive linking.
@@ -0,0 +1,32 @@
add_subdirectory
----------------
Add a subdirectory to the build.
.. code-block:: cmake
add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL] [SYSTEM])
Adds a subdirectory to the build. The ``source_dir`` specifies the
directory in which the source ``CMakeLists.txt`` and code files are
located. If it is a relative path, it will be evaluated with respect
to the current directory (the typical usage), but it may also be an
absolute path. The ``binary_dir`` specifies the directory in which to
place the output files. If it is a relative path, it will be evaluated
with respect to the current output directory, but it may also be an
absolute path. If ``binary_dir`` is not specified, the value of
``source_dir``, before expanding any relative path, will be used (the
typical usage). The ``CMakeLists.txt`` file in the specified source
directory will be processed immediately by CMake before processing in
the current input file continues beyond this command.
If the ``EXCLUDE_FROM_ALL`` argument is provided then the
:prop_dir:`EXCLUDE_FROM_ALL` property will be set on the added directory.
This will exclude the directory from a default build. See the directory
property :prop_dir:`EXCLUDE_FROM_ALL` for full details.
.. versionadded:: 3.25
If the ``SYSTEM`` argument is provided, the :prop_dir:`SYSTEM` directory
property of the subdirectory will be set to true. This property is
used to initialize the :prop_tgt:`SYSTEM` property of each non-imported
target created in that subdirectory.
@@ -0,0 +1,147 @@
add_test
--------
Add a test to the project to be run by :manual:`ctest(1)`.
.. code-block:: cmake
add_test(NAME <name> COMMAND <command> [<arg>...]
[CONFIGURATIONS <config>...]
[WORKING_DIRECTORY <dir>]
[COMMAND_EXPAND_LISTS]
[BUILD_DEPENDS <dependencies>...])
Adds a test called ``<name>``. The test name may contain arbitrary
characters, expressed as a :ref:`Quoted Argument` or :ref:`Bracket Argument`
if necessary. See policy :policy:`CMP0110`.
CMake only generates tests if the :command:`enable_testing` command has been
invoked. The :module:`CTest` module invokes ``enable_testing`` automatically
unless :variable:`BUILD_TESTING` is set to ``OFF``.
Tests added with the ``add_test(NAME)`` signature support using
:manual:`generator expressions <cmake-generator-expressions(7)>`
in test properties set by :command:`set_property(TEST)` or
:command:`set_tests_properties`. Test properties may only be set in the
directory the test is created in.
``add_test`` options are:
``COMMAND``
Specify the test command-line.
If ``<command>`` specifies an executable target created by
:command:`add_executable`:
* It will automatically be replaced by the location of the executable
created at build time.
* .. versionadded:: 3.3
The target's :prop_tgt:`CROSSCOMPILING_EMULATOR`, if set, will be
used to run the command on the host::
<emulator> <command>
.. versionchanged:: 3.29
The emulator is used only when
:variable:`cross-compiling <CMAKE_CROSSCOMPILING>`.
See policy :policy:`CMP0158`.
* .. versionadded:: 3.29
The target's :prop_tgt:`TEST_LAUNCHER`, if set, will be
used to launch the command::
<launcher> <command>
If the :prop_tgt:`CROSSCOMPILING_EMULATOR` is also set, both are used::
<launcher> <emulator> <command>
* .. versionadded:: 4.4
When the :variable:`CMAKE_TEST_BUILD_DEPENDS` variable is enabled,
the :ref:`Ninja Generators` generate a convenience build target named
``test_prep/<name>`` that depends on the test executable target. Building
this target ensures the executable is up-to-date before the test runs.
Additionally, targets referenced by the test command via generator
expressions are added as dependencies of the ``test_prep/<name>`` target.
If multiple tests in different directories share the same name, their
dependencies are merged into a single ``test_prep/<name>`` target.
Tests with names that are not valid target names are excluded from this
behavior.
The ``BUILD_DEPENDS`` keyword can be used to add explicit build
dependencies.
The command may be specified using
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``CONFIGURATIONS``
Restrict execution of the test only to the named configurations.
``WORKING_DIRECTORY``
Set the test property :prop_test:`WORKING_DIRECTORY` in which to execute the
test. If not specified, the test will be run in
:variable:`CMAKE_CURRENT_BINARY_DIR`. The working directory may be specified
using :manual:`generator expressions <cmake-generator-expressions(7)>`.
``BUILD_DEPENDS``
.. versionadded:: 4.4
Specify a list of targets or files that must be built before the test can
run. Each dependency is added to the ``test_prep/<name>`` build target
described above when :variable:`CMAKE_TEST_BUILD_DEPENDS` is enabled
with the :ref:`Ninja Generators`. The test name must be a valid target name
in order to list build dependencies with this keyword.
``COMMAND_EXPAND_LISTS``
.. versionadded:: 3.16
Lists in ``COMMAND`` arguments will be expanded, including those created with
:manual:`generator expressions <cmake-generator-expressions(7)>`.
If the test command exits with code ``0`` the test passes. Non-zero exit code
is a "failed" test. The test property :prop_test:`WILL_FAIL` inverts this
logic. Note that system-level test failures such as segmentation faults or
heap errors will still fail the test even if ``WILL_FAIL`` is true. Output
written to stdout or stderr is captured by :manual:`ctest(1)` and only
affects the pass/fail status via the :prop_test:`PASS_REGULAR_EXPRESSION`,
:prop_test:`FAIL_REGULAR_EXPRESSION`, or :prop_test:`SKIP_REGULAR_EXPRESSION`
test properties.
.. versionadded:: 3.16
Added :prop_test:`SKIP_REGULAR_EXPRESSION` property.
Example usage:
.. code-block:: cmake
add_test(NAME mytest
COMMAND testDriver --config $<CONFIG>
--exe $<TARGET_FILE:myexe>)
This creates a test ``mytest`` whose command runs a ``testDriver`` tool
passing the configuration name and the full path to the executable
file produced by target ``myexe``.
---------------------------------------------------------------------
The command syntax above is recommended over the older, less flexible form:
.. code-block:: cmake
add_test(<name> <command> [<arg>...])
Add a test called ``<name>`` with the given command-line.
Unlike the above ``NAME`` signature, target names are not supported
in the command-line. Furthermore, tests added with this signature do not
support :manual:`generator expressions <cmake-generator-expressions(7)>`
in the command-line or test properties, and the :prop_tgt:`TEST_LAUNCHER`
and :prop_tgt:`CROSSCOMPILING_EMULATOR` target properties are not supported.
@@ -0,0 +1,24 @@
aux_source_directory
--------------------
Find all source files in a directory.
.. code-block:: cmake
aux_source_directory(<dir> <variable>)
Collects the names of all the source files in the specified directory
and stores the list in the ``<variable>`` provided. This command is
intended to be used by projects that use explicit template
instantiation. Template instantiation files can be stored in a
``Templates`` subdirectory and collected automatically using this
command to avoid manually listing all instantiations.
It is tempting to use this command to avoid writing the list of source
files for a library or executable target. While this seems to work,
there is no way for CMake to generate a build system that knows when a
new source file has been added. Normally the generated build system
knows when it needs to rerun CMake because the ``CMakeLists.txt`` file is
modified to add a new source. When the source is just added to the
directory without modifying this file, one would have to manually
rerun CMake to generate a build system incorporating the new file.
@@ -0,0 +1,87 @@
block
-----
.. versionadded:: 3.25
Evaluate a group of commands with a dedicated variable and/or policy scope.
.. code-block:: cmake
block([SCOPE_FOR [DIAGNOSTICS] [POLICIES] [VARIABLES]]
[PROPAGATE <var-name>...])
<commands>
endblock()
All commands between ``block()`` and the matching :command:`endblock` are
recorded without being invoked. Once the :command:`endblock` is evaluated, the
recorded list of commands is invoked inside the requested scopes, then the
scopes created by the ``block()`` command are removed.
``SCOPE_FOR``
Specify which scopes must be created.
``DIAGNOSTICS``
.. versionadded:: 4.4
Create a new diagnostic scope. This is equivalent to
:command:`cmake_diagnostic(PUSH)` with an automatic
:command:`cmake_diagnostic(POP)` when leaving the block scope.
``POLICIES``
Create a new policy scope. This is equivalent to
:command:`cmake_policy(PUSH)` with an automatic
:command:`cmake_policy(POP)` when leaving the block scope.
``VARIABLES``
Create a new variable scope.
If ``SCOPE_FOR`` is not specified, this is equivalent to:
.. code-block:: cmake
block(SCOPE_FOR VARIABLES POLICIES DIAGNOSTICS)
``PROPAGATE``
When a variable scope is created by the :command:`block` command, this
option sets or unsets the specified variables in the parent scope. This is
equivalent to :command:`set(PARENT_SCOPE)` or :command:`unset(PARENT_SCOPE)`
commands.
.. code-block:: cmake
set(var1 "INIT1")
set(var2 "INIT2")
set(var3 "INIT3")
block(PROPAGATE var1 var2)
set(var1 "VALUE1")
unset(var2)
set(var3 "VALUE3")
endblock()
# Now var1 holds VALUE1, var2 is unset, and var3 holds the initial value INIT3
This option is only allowed when a variable scope is created. An error will
be raised in the other cases.
When the ``block()`` is inside a :command:`foreach` or :command:`while`
command, the :command:`break` and :command:`continue` commands can be used
inside the block.
.. code-block:: cmake
while(TRUE)
block()
...
# the break() command will terminate the while() command
break()
endblock()
endwhile()
See Also
^^^^^^^^
* :command:`endblock`
* :command:`return`
* :command:`cmake_policy`
@@ -0,0 +1,12 @@
break
-----
Break from an enclosing foreach or while loop.
.. code-block:: cmake
break()
Breaks from an enclosing :command:`foreach` or :command:`while` loop.
See also the :command:`continue` command.
@@ -0,0 +1,51 @@
build_command
-------------
Get a command line to build the current project.
This is mainly intended for internal use by the :module:`CTest` module.
.. code-block:: cmake
build_command(<variable>
[CONFIGURATION <config>]
[PARALLEL_LEVEL <parallel>]
[TARGET <target>]
[PROJECT_NAME <projname>] # legacy, causes warning
)
Sets the given ``<variable>`` to a command-line string of the form::
<cmake> --build . [--config <config>] [--parallel <parallel>] [--target <target>...]
where ``<cmake>`` is the location of the :manual:`cmake(1)` command-line
tool, and ``<config>``, ``<parallel>`` and ``<target>`` are the values
provided to the ``CONFIGURATION``, ``PARALLEL_LEVEL`` and ``TARGET``
options, if any. In CMake versions prior to 4.0, a trailing ``-- -i``
option was added for :ref:`Makefile Generators` if policy :policy:`CMP0061`
was not set to ``NEW``.
When invoked, this :option:`cmake --build` command line will launch the
underlying build system tool.
.. versionadded:: 3.21
The ``PARALLEL_LEVEL`` argument can be used to set the
:cmake-build-option:`--parallel` flag.
.. code-block:: cmake
build_command(<cachevariable> <makecommand>)
This second signature is deprecated, but still available for backwards
compatibility. Use the first signature instead.
It sets the given ``<cachevariable>`` to a command-line string as
above but without the :cmake-build-option:`--target` option.
The ``<makecommand>`` is ignored but should be the full path to
devenv, nmake, make or one of the end user build tools
for legacy invocations.
.. note::
In CMake versions prior to 3.0 this command returned a command
line that directly invokes the native build tool for the current
generator. Their implementation of the ``PROJECT_NAME`` option
had no useful effects, so CMake now warns on use of the option.
@@ -0,0 +1,15 @@
build_name
----------
Disallowed since version 3.0. See CMake Policy :policy:`CMP0036`.
Use ``${CMAKE_SYSTEM}`` and ``${CMAKE_CXX_COMPILER}`` instead.
.. code-block:: cmake
build_name(variable)
Sets the specified variable to a string representing the platform and
compiler settings. These values are now available through the
:variable:`CMAKE_SYSTEM` and
:variable:`CMAKE_CXX_COMPILER <CMAKE_<LANG>_COMPILER>` variables.
@@ -0,0 +1,156 @@
cmake_diagnostic
----------------
.. versionadded:: 4.4
Manage CMake Diagnostic settings. See the :manual:`cmake-diagnostics(7)`
manual for a list of available categories.
Synopsis
^^^^^^^^
.. parsed-literal::
`Setting Diagnostics`_
cmake_diagnostic(`SET`_ <category> <action> [RECURSE])
cmake_diagnostic(`PROMOTE`_ <category> <action> [NO_RECURSE])
cmake_diagnostic(`DEMOTE`_ <category> <action> [NO_RECURSE])
`Checking Diagnostic Actions`_
cmake_diagnostic(`GET`_ <diagnostic> <out-var>)
`CMake Diagnostic Stack`_
cmake_diagnostic(`PUSH`_)
cmake_diagnostic(`POP`_)
Setting Diagnostics
^^^^^^^^^^^^^^^^^^^
.. signature::
cmake_diagnostic(SET CMD_<CATEGORY> <action> [RECURSE])
cmake_diagnostic(PROMOTE CMD_<CATEGORY> <action> [NO_RECURSE])
cmake_diagnostic(DEMOTE CMD_<CATEGORY> <action> [NO_RECURSE])
:target:
SET
PROMOTE
DEMOTE
Set or alter the action taken when a diagnostic belonging to a particular
category is triggered.
The ``SET`` subcommand sets the action for the specified diagnostic category.
The ``PROMOTE`` subcommand increases the severity for the specified diagnostic
category, or does nothing if the action was already set to an equal or higher
severity. The ``DEMOTE`` subcommand decreases the severity for the specified
diagnostic category, or does nothing if the action was already set to an equal
or lower severity.
The possible ``<action>``\ s (in order of severity) are:
``IGNORE``
Do nothing.
``WARN``
Report a warning and continue processing.
``SEND_ERROR``
Report an error, continue processing, but skip generation.
The :manual:`cmake(1)` executable will return a non-zero
:ref:`exit code <CMake Exit Code>`.
``FATAL_ERROR``
Report an error, stop processing and generation.
The :manual:`cmake(1)` executable will return a non-zero
:ref:`exit code <CMake Exit Code>`.
Some diagnostic categories are hierarchical. The ``RECURSE`` and
``NO_RECURSE`` options determine whether changing the action for a diagnostic
category also modifies any child categories. By default, the ``PROMOTE`` and
``DEMOTE`` subcommands are recursive, while the ``SET`` subcommand is not.
Note that the alteration for child categories is independent of the prior
action set on any parents; that is, ``PROMOTE`` and ``DEMOTE``, when operating
recursively, will operate on all child categories even if a parent category's
action was not altered.
Checking Diagnostic Actions
^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. signature:: cmake_diagnostic(GET CMD_<CATEGORY> <variable>)
:target: GET
Check what action is currently specified for a diagnostic category.
The output ``<variable>`` value will be one of ``IGNORE``, ``WARN``,
``SEND_ERROR`` or ``FATAL_ERROR``.
CMake Diagnostic Stack
^^^^^^^^^^^^^^^^^^^^^^
CMake keeps diagnostic settings on a stack, so changes made by the
``cmake_diagnostic`` command affect only the top of the stack. A new entry on
the diagnostic stack is managed automatically for each subdirectory to protect
its parents and siblings. CMake also manages a new entry for scripts loaded by
:command:`include` and :command:`find_package` commands except when invoked
with the ``NO_DIAGNOSTIC_SCOPE`` option. The ``cmake_diagnostic`` command
provides an interface to manage custom entries on the diagnostic stack:
.. signature:: cmake_diagnostic(PUSH)
Create a new entry on the diagnostic stack.
.. signature:: cmake_diagnostic(POP)
Remove the last diagnostic stack entry created with
``cmake_diagnostic(PUSH)``.
Each ``PUSH`` must have a matching ``POP`` to erase any changes.
This is useful to make temporary changes to diagnostic settings.
Calls to the :command:`cmake_diagnostic(SET)`,
:command:`cmake_diagnostic(PROMOTE)`, or :command:`cmake_diagnostic(DEMOTE)`
commands influence only the current top of the diagnostic stack.
The :command:`block(SCOPE_FOR DIAGNOSTICS)` command offers a more flexible
and more secure way to manage the diagnostic stack. The pop action is done
automatically when leaving the block scope, so there is no need to
precede each :command:`return` with a call to :command:`cmake_diagnostic(POP)`.
.. code-block:: cmake
# stack management with cmake_diagnostic()
function(my_func)
cmake_diagnostic(PUSH)
cmake_diagnostic(SET ...)
if (<cond1>)
...
cmake_diagnostic(POP)
return()
elseif(<cond2>)
...
cmake_diagnostic(POP)
return()
endif()
...
cmake_diagnostic(POP)
endfunction()
# stack management with block()/endblock()
function(my_func)
block(SCOPE_FOR DIAGNOSTICS)
cmake_diagnostic(SET ...)
if (<cond1>)
...
return()
elseif(<cond2>)
...
return()
endif()
...
endblock()
endfunction()
Commands created by the :command:`function` and :command:`macro` commands
record diagnostic settings when they are created and use the pre-record
diagnostics when they are invoked. If the function or macro implementation
sets diagnostics, the changes automatically propagate up through callers until
they reach the closest nested diagnostic stack entry.
@@ -0,0 +1,78 @@
cmake_file_api
--------------
.. versionadded:: 3.27
Enables interacting with the :manual:`CMake file API <cmake-file-api(7)>`.
.. signature::
cmake_file_api(QUERY ...)
The ``QUERY`` subcommand adds a file API query for the current CMake
invocation.
.. code-block:: cmake
cmake_file_api(
QUERY
API_VERSION <version>
[CODEMODEL <versions>...]
[CACHE <versions>...]
[CMAKEFILES <versions>...]
[TOOLCHAINS <versions>...]
)
The ``API_VERSION`` must always be given. Currently, the only supported
value for ``<version>`` is 1. See :ref:`file-api v1` for details of the
reply content and location.
Each of the optional keywords ``CODEMODEL``, ``CACHE``, ``CMAKEFILES`` and
``TOOLCHAINS`` correspond to one of the object kinds that can be requested
by the project. The ``configureLog`` object kind cannot be set with this
command, since it must be set before CMake starts reading the top level
``CMakeLists.txt`` file.
For each of the optional keywords, the ``<versions>`` list must contain one
or more version values of the form ``major`` or ``major.minor``, where
``major`` and ``minor`` are integers. Projects should list the versions they
accept in their preferred order, as only the first supported value from the
list will be selected. The command will ignore versions with a ``major``
version higher than any major version it supports for that object kind.
It will raise an error if it encounters an invalid version number, or if none
of the requested versions is supported.
For each type of object kind requested, a query equivalent to a shared,
stateless query will be added internally. No query file will be created in
the file system. The reply *will* be written to the file system at
generation time.
It is not an error to add a query for the same thing more than once, whether
from query files or from multiple calls to ``cmake_file_api(QUERY)``.
The final set of queries will be a merged combination of all queries
specified on disk and queries submitted by the project.
Example
^^^^^^^
A project may want to use replies from the file API at build time to implement
some form of verification task. Instead of relying on something outside of
CMake to create a query file, the project can use ``cmake_file_api(QUERY)``
to request the required information for the current run. It can then create
a custom command to run at build time, knowing that the requested information
should always be available.
.. code-block:: cmake
cmake_file_api(
QUERY
API_VERSION 1
CODEMODEL 2.3
TOOLCHAINS 1
)
add_custom_target(verify_project
COMMAND ${CMAKE_COMMAND}
-D BUILD_DIR=${CMAKE_BINARY_DIR}
-D CONFIG=$<CONFIG>
-P ${CMAKE_CURRENT_SOURCE_DIR}/verify_project.cmake
)
@@ -0,0 +1,486 @@
cmake_host_system_information
-----------------------------
Query various host system information.
Synopsis
^^^^^^^^
.. parsed-literal::
`Query host system specific information`_
cmake_host_system_information(RESULT <variable> `QUERY`_ <key> ...)
`Query the Windows registry`_
cmake_host_system_information(RESULT <variable> `QUERY WINDOWS_REGISTRY`_ <key> ...)
Query host system specific information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. signature::
cmake_host_system_information(RESULT <variable> QUERY <key> ...)
:target:
QUERY
Queries system information of the host system on which cmake runs.
One or more ``<key>`` can be provided to select the information to be
queried. The list of queried values is stored in ``<variable>``.
``<key>`` can be one of the following values:
``NUMBER_OF_LOGICAL_CORES``
Number of logical cores
``NUMBER_OF_PHYSICAL_CORES``
Number of physical cores
``HOSTNAME``
Hostname
``FQDN``
Fully qualified domain name
``TOTAL_VIRTUAL_MEMORY``
Total virtual memory in MiB [#mebibytes]_
``AVAILABLE_VIRTUAL_MEMORY``
Available virtual memory in MiB [#mebibytes]_
``TOTAL_PHYSICAL_MEMORY``
Total physical memory in MiB [#mebibytes]_
``AVAILABLE_PHYSICAL_MEMORY``
Available physical memory in MiB [#mebibytes]_
``IS_64BIT``
.. versionadded:: 3.10
One if processor is 64Bit
``HAS_FPU``
.. versionadded:: 3.10
One if processor has floating point unit
``HAS_MMX``
.. versionadded:: 3.10
One if processor supports MMX instructions
``HAS_MMX_PLUS``
.. versionadded:: 3.10
One if processor supports Ext. MMX instructions
``HAS_SSE``
.. versionadded:: 3.10
One if processor supports SSE instructions
``HAS_SSE2``
.. versionadded:: 3.10
One if processor supports SSE2 instructions
``HAS_SSE_FP``
.. versionadded:: 3.10
One if processor supports SSE FP instructions
``HAS_SSE_MMX``
.. versionadded:: 3.10
One if processor supports SSE MMX instructions
``HAS_AMD_3DNOW``
.. versionadded:: 3.10
One if processor supports 3DNow instructions
``HAS_AMD_3DNOW_PLUS``
.. versionadded:: 3.10
One if processor supports 3DNow+ instructions
``HAS_IA64``
.. versionadded:: 3.10
One if IA64 processor emulating x86
``HAS_SERIAL_NUMBER``
.. versionadded:: 3.10
One if processor has serial number
``HAS_APIC``
.. versionadded:: 4.3
One if processor supports APIC
``HAS_L1_CACHE``
.. versionadded:: 4.3
One if processor has L1 cache
``PROCESSOR_SERIAL_NUMBER``
.. versionadded:: 3.10
Processor serial number
``PROCESSOR_NAME``
.. versionadded:: 3.10
Human readable processor name
``PROCESSOR_DESCRIPTION``
.. versionadded:: 3.10
Human readable full processor description
``LOCALE_CHARSET``
.. versionadded:: 4.3
The locale's character set, if known, otherwise empty.
This is the :ref:`encoding <CMake Language Encoding>` expected
in :manual:`cmake-language(7)` files and scripts:
* On Windows, this is always ``UTF-8``.
* On UNIX and macOS, this is based on the current locale.
``OS_NAME``
.. versionadded:: 3.10
The host operating system name:
* On UNIX platforms, this is ``uname -s``.
* On Apple platforms, this is ``sw_vers -productName``.
* On Windows, this is ``Windows``.
See also :variable:`CMAKE_HOST_SYSTEM_NAME`.
``OS_RELEASE``
.. versionadded:: 3.10
The OS sub-type e.g. on Windows ``Professional``
``OS_VERSION``
.. versionadded:: 3.10
The OS build ID
``OS_PLATFORM``
.. versionadded:: 3.10
See :variable:`CMAKE_HOST_SYSTEM_PROCESSOR`
``MSYSTEM_PREFIX``
.. versionadded:: 3.28
Available only on Windows hosts. In a MSYS or MinGW development
environment that sets the ``MSYSTEM`` environment variable, this
is its installation prefix. Otherwise, this is the empty string.
``FAMILY_ID``
.. versionadded:: 4.3
The processor family name
``MODEL_ID``
.. versionadded:: 4.3
The processor model ID
``MODEL_NAME``
.. versionadded:: 4.3
The processor model name
``PROCESSOR_APIC_ID``
.. versionadded:: 4.3
The processor APIC ID
``PROCESSOR_CACHE_SIZE``
.. versionadded:: 4.3
The processor L1 cache size
``PROCESSOR_CLOCK_FREQUENCY``
.. versionadded:: 4.3
The processor clock frequency
``VENDOR_ID``
.. versionadded:: 4.3
The processor vendor ID
``VENDOR_STRING``
.. versionadded:: 4.3
The processor vendor string
``DISTRIB_INFO``
.. versionadded:: 3.22
Read :file:`/etc/os-release` file and define the given ``<variable>``
into a list of read variables
``DISTRIB_<name>``
.. versionadded:: 3.22
Get the ``<name>`` variable (see `man 5 os-release`_) if it exists in the
:file:`/etc/os-release` file
Example:
.. code-block:: cmake
cmake_host_system_information(RESULT PRETTY_NAME QUERY DISTRIB_PRETTY_NAME)
message(STATUS "${PRETTY_NAME}")
cmake_host_system_information(RESULT DISTRO QUERY DISTRIB_INFO)
foreach(VAR IN LISTS DISTRO)
message(STATUS "${VAR}=`${${VAR}}`")
endforeach()
Output::
-- Ubuntu 20.04.2 LTS
-- DISTRO_BUG_REPORT_URL=`https://bugs.launchpad.net/ubuntu/`
-- DISTRO_HOME_URL=`https://www.ubuntu.com/`
-- DISTRO_ID=`ubuntu`
-- DISTRO_ID_LIKE=`debian`
-- DISTRO_NAME=`Ubuntu`
-- DISTRO_PRETTY_NAME=`Ubuntu 20.04.2 LTS`
-- DISTRO_PRIVACY_POLICY_URL=`https://www.ubuntu.com/legal/terms-and-policies/privacy-policy`
-- DISTRO_SUPPORT_URL=`https://help.ubuntu.com/`
-- DISTRO_UBUNTU_CODENAME=`focal`
-- DISTRO_VERSION=`20.04.2 LTS (Focal Fossa)`
-- DISTRO_VERSION_CODENAME=`focal`
-- DISTRO_VERSION_ID=`20.04`
If :file:`/etc/os-release` file is not found, the command tries to gather OS
identification via fallback scripts. The fallback script can use `various
distribution-specific files`_ to collect OS identification data and map it
into `man 5 os-release`_ variables.
Fallback Interface Variables
""""""""""""""""""""""""""""
.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_SCRIPTS
In addition to the scripts shipped with CMake, a user may append full
paths of their script(s) to this list. The script filename has the
following format: ``NNN-<name>.cmake``, where ``NNN`` is three digits
used to apply collected scripts in a specific order.
.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_<varname>
Variables collected by the user provided fallback script
ought to be assigned to CMake variables using this naming
convention. Example, the ``ID`` variable from the manual becomes
``CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID``.
.. variable:: CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
The fallback script ought to store names of all assigned
``CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_<varname>`` variables in this list.
Example:
.. code-block:: cmake
# 000-FallbackScript.cmake
#
# Try to detect some old distribution
# See also
# - http://linuxmafia.com/faq/Admin/release-files.html
#
if(NOT EXISTS "${CMAKE_SYSROOT}/etc/foobar-release")
return()
endif()
# Get the first string only
file(
STRINGS "${CMAKE_SYSROOT}/etc/foobar-release" CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT
LIMIT_COUNT 1
)
#
# Example:
#
# Foobar distribution release 1.2.3 (server)
#
if(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT MATCHES "Foobar distribution release ([0-9\.]+) .*")
set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME Foobar)
set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME "${CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT}")
set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID foobar)
set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION ${CMAKE_MATCH_1})
set(CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID ${CMAKE_MATCH_1})
list(
APPEND CMAKE_GET_OS_RELEASE_FALLBACK_RESULT
CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_NAME
CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_PRETTY_NAME
CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_ID
CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION
CMAKE_GET_OS_RELEASE_FALLBACK_RESULT_VERSION_ID
)
endif()
unset(CMAKE_GET_OS_RELEASE_FALLBACK_CONTENT)
Then this script can be applied as a fallback to determine the missing host
system information:
.. code-block:: cmake
list(
APPEND
CMAKE_GET_OS_RELEASE_FALLBACK_SCRIPTS
${CMAKE_CURRENT_SOURCE_DIR}/000-FallbackScript.cmake
)
cmake_host_system_information(RESULT info QUERY DISTRIB_INFO)
.. rubric:: Footnotes
.. [#mebibytes] One MiB (mebibyte) is equal to 1024x1024 bytes.
.. _man 5 os-release: https://www.freedesktop.org/software/systemd/man/latest/os-release.html
.. _various distribution-specific files: http://linuxmafia.com/faq/Admin/release-files.html
Query the Windows registry
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.24
.. signature::
cmake_host_system_information(RESULT <variable>
QUERY WINDOWS_REGISTRY <key> [VALUE_NAMES|SUBKEYS|VALUE <name>]
[VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)]
[SEPARATOR <separator>]
[ERROR_VARIABLE <result>])
:target:
QUERY WINDOWS_REGISTRY
Performs query operations on local computer registry subkey. Returns a list of
subkeys or value names that are located under the specified subkey in the
registry or the data of the specified value name. The result of the queried
entity is stored in ``<variable>``.
.. note::
Querying registry for any other platforms than ``Windows``, including
``CYGWIN``, will always returns an empty string and sets an error message in
the variable specified with sub-option ``ERROR_VARIABLE``.
``<key>`` specify the full path of a subkey on the local computer. The
``<key>`` must include a valid root key. Valid root keys for the local computer
are:
* ``HKLM`` or ``HKEY_LOCAL_MACHINE``
* ``HKCU`` or ``HKEY_CURRENT_USER``
* ``HKCR`` or ``HKEY_CLASSES_ROOT``
* ``HKU`` or ``HKEY_USERS``
* ``HKCC`` or ``HKEY_CURRENT_CONFIG``
And, optionally, the path to a subkey under the specified root key. The path
separator can be the slash or the backslash. ``<key>`` is not case sensitive.
For example:
.. code-block:: cmake
cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKLM")
cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware")
cmake_host_system_information(RESULT result QUERY WINDOWS_REGISTRY "HKCU\\SOFTWARE\\Kitware")
``VALUE_NAMES``
Request the list of value names defined under ``<key>``. If a default value
is defined, it will be identified with the special name ``(default)``.
``SUBKEYS``
Request the list of subkeys defined under ``<key>``.
``VALUE <name>``
Request the data stored in value named ``<name>``. If ``VALUE`` is not
specified or argument is the special name ``(default)``, the content of the
default value, if any, will be returned.
.. code-block:: cmake
# query default value for HKLM/SOFTWARE/Kitware key
cmake_host_system_information(RESULT result
QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware")
# query default value for HKLM/SOFTWARE/Kitware key using special value name
cmake_host_system_information(RESULT result
QUERY WINDOWS_REGISTRY "HKLM/SOFTWARE/Kitware"
VALUE "(default)")
Supported types are:
* ``REG_SZ``.
* ``REG_EXPAND_SZ``. The returned data is expanded.
* ``REG_MULTI_SZ``. The returned is expressed as a CMake list. See also
``SEPARATOR`` sub-option.
* ``REG_DWORD``.
* ``REG_QWORD``.
For all other types, an empty string is returned.
``VIEW``
Specify which registry views must be queried. When not specified, ``BOTH``
view is used.
``64``
Query the 64bit registry. On ``32bit Windows``, returns always an empty
string.
``32``
Query the 32bit registry.
``64_32``
For ``VALUE`` sub-option or default value, query the registry using view
``64``, and if the request failed, query the registry using view ``32``.
For ``VALUE_NAMES`` and ``SUBKEYS`` sub-options, query both views (``64``
and ``32``) and merge the results (sorted and duplicates removed).
``32_64``
For ``VALUE`` sub-option or default value, query the registry using view
``32``, and if the request failed, query the registry using view ``64``.
For ``VALUE_NAMES`` and ``SUBKEYS`` sub-options, query both views (``32``
and ``64``) and merge the results (sorted and duplicates removed).
``HOST``
Query the registry matching the architecture of the host: ``64`` on ``64bit
Windows`` and ``32`` on ``32bit Windows``.
``TARGET``
Query the registry matching the architecture specified by
:variable:`CMAKE_SIZEOF_VOID_P` variable. If not defined, fallback to
``HOST`` view.
``BOTH``
Query both views (``32`` and ``64``). The order depends of the following
rules: If :variable:`CMAKE_SIZEOF_VOID_P` variable is defined. Use the
following view depending of the content of this variable:
* ``8``: ``64_32``
* ``4``: ``32_64``
If :variable:`CMAKE_SIZEOF_VOID_P` variable is not defined, rely on
architecture of the host:
* ``64bit``: ``64_32``
* ``32bit``: ``32``
``SEPARATOR``
Specify the separator character for ``REG_MULTI_SZ`` type. When not
specified, the character ``\0`` is used.
``ERROR_VARIABLE <result>``
Returns any error raised during query operation. In case of success, the
variable holds an empty string.
@@ -0,0 +1,116 @@
cmake_instrumentation
---------------------
.. versionadded:: 4.3
Enables interacting with the
:manual:`CMake Instrumentation API <cmake-instrumentation(7)>`.
This allows for configuring instrumentation at the project-level.
.. code-block:: cmake
cmake_instrumentation(
API_VERSION <version>
DATA_VERSION <version>
[HOOKS <hooks>...]
[OPTIONS <options>...]
[CALLBACK <callback>]
[CUSTOM_CONTENT <name> <type> <content>]
)
The ``API_VERSION`` and ``DATA_VERSION`` must always be given.
``API_VERSION`` is an integer. Currently, the only supported value is ``1``.
See :ref:`cmake-instrumentation API v1` for details.
``DATA_VERSION`` is a version value of the form ``major`` or ``major.minor``.
Currently, the maximum supported version is ``1.1``. See
:ref:`cmake-instrumentation Data Version` for details.
Each of the optional keywords ``HOOKS``, ``OPTIONS``, and ``CALLBACK``
correspond to one of the parameters to the :ref:`cmake-instrumentation v1 Query Files`.
The ``CALLBACK`` keyword can be provided multiple times to create multiple callbacks.
Whenever ``cmake_instrumentation`` is invoked, a query file is generated in
``<build>/.cmake/instrumentation/v1/query/generated`` to enable instrumentation
with the provided arguments.
.. _`cmake_instrumentation CUSTOM_CONTENT`:
Custom CMake Content
^^^^^^^^^^^^^^^^^^^^
The ``CUSTOM_CONTENT`` argument specifies certain data from configure time to
include in each :ref:`cmake-instrumentation v1 CMake Content File`. This
may be used to associate instrumentation data with certain information about its
configuration, such as the optimization level or whether it is part of a
coverage build.
``CUSTOM_CONTENT`` expects ``name``, ``type`` and ``content`` arguments.
``name`` is a specifier to identify the content being reported.
``type`` specifies how the content should be interpreted. Supported values are:
* ``STRING`` the content is a string.
* ``BOOL`` the content should be interpreted as a boolean. It will be ``true``
under the same conditions that ``if()`` would be true for the given value.
* ``LIST`` the content is a CMake ``;`` separated list that should be parsed.
* ``JSON`` the content should be parsed as a JSON string. This can be a
number such as ``1`` or ``5.0``, a quoted string such as ``\"string\"``,
a boolean value ``true``/``false``, or a JSON object such as
``{ \"key\" : \"value\" }`` that may be constructed using
``string(JSON ...)`` commands.
``content`` is the actual content to report.
Example
^^^^^^^
The following example shows an invocation of the command and its
equivalent JSON query file.
.. code-block:: cmake
cmake_instrumentation(
API_VERSION 1
DATA_VERSION 1.0
HOOKS postGenerate preCMakeBuild postCMakeBuild
OPTIONS staticSystemInformation dynamicSystemInformation compileTrace trace
CALLBACK ${CMAKE_COMMAND} -P /path/to/handle_data.cmake
CALLBACK ${CMAKE_COMMAND} -P /path/to/handle_data_2.cmake
CUSTOM_CONTENT myString STRING string
CUSTOM_CONTENT myList LIST "item1;item2"
CUSTOM_CONTENT myObject JSON "{ \"key\" : \"value\" }"
)
.. code-block:: json
{
"version": 1,
"hooks": [
"postGenerate", "preCMakeBuild", "postCMakeBuild"
],
"options": [
"staticSystemInformation", "dynamicSystemInformation", "compileTrace", "trace"
],
"callbacks": [
"/path/to/cmake -P /path/to/handle_data.cmake",
"/path/to/cmake -P /path/to/handle_data_2.cmake"
]
}
This will also result in the following content included in each
:ref:`cmake-instrumentation v1 CMake Content File`:
.. code-block:: json
"custom": {
"myString": "string",
"myList": [
"item1", "item2"
],
"myObject": {
"key": "value"
}
}
@@ -0,0 +1,559 @@
cmake_language
--------------
.. versionadded:: 3.18
Call meta-operations on CMake commands.
Synopsis
^^^^^^^^
.. parsed-literal::
cmake_language(`CALL`_ <command> [<arg>...])
cmake_language(`EVAL`_ CODE <code>...)
cmake_language(`DEFER`_ <options>... CALL <command> [<arg>...])
cmake_language(`SET_DEPENDENCY_PROVIDER`_ <command> SUPPORTED_METHODS <methods>...)
cmake_language(`GET_MESSAGE_LOG_LEVEL`_ <out-var>)
cmake_language(`EXIT`_ <exit-code>)
cmake_language(`TRACE`_ <boolean> ...)
Introduction
^^^^^^^^^^^^
This command will call meta-operations on built-in CMake commands or
those created via the :command:`macro` or :command:`function` commands.
``cmake_language`` does not introduce a new variable or policy scope.
Calling Commands
^^^^^^^^^^^^^^^^
.. signature::
cmake_language(CALL <command> [<arg>...])
Calls the named ``<command>`` with the given arguments (if any).
For example, the code:
.. code-block:: cmake
set(message_command "message")
cmake_language(CALL ${message_command} STATUS "Hello World!")
is equivalent to
.. code-block:: cmake
message(STATUS "Hello World!")
.. note::
To ensure consistency of the code, the following commands are not allowed:
* ``if`` / ``elseif`` / ``else`` / ``endif``
* ``block`` / ``endblock``
* ``while`` / ``endwhile``
* ``foreach`` / ``endforeach``
* ``function`` / ``endfunction``
* ``macro`` / ``endmacro``
Evaluating Code
^^^^^^^^^^^^^^^
.. signature::
cmake_language(EVAL CODE <code>...)
:target: EVAL
Evaluates the ``<code>...`` as CMake code.
For example, the code:
.. code-block:: cmake
set(A TRUE)
set(B TRUE)
set(C TRUE)
set(condition "(A AND B) OR C")
cmake_language(EVAL CODE "
if (${condition})
message(STATUS TRUE)
else()
message(STATUS FALSE)
endif()"
)
is equivalent to
.. code-block:: cmake
set(A TRUE)
set(B TRUE)
set(C TRUE)
set(condition "(A AND B) OR C")
file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/eval.cmake "
if (${condition})
message(STATUS TRUE)
else()
message(STATUS FALSE)
endif()"
)
include(${CMAKE_CURRENT_BINARY_DIR}/eval.cmake)
Deferring Calls
^^^^^^^^^^^^^^^
.. versionadded:: 3.19
.. signature::
cmake_language(DEFER <options>... CALL <command> [<arg>...])
Schedules a call to the named ``<command>`` with the given arguments (if any)
to occur at a later time. By default, deferred calls are executed as if
written at the end of the current directory's ``CMakeLists.txt`` file,
except that they run even after a :command:`return` call. Variable
references in arguments are evaluated at the time the deferred call is
executed.
The options are:
``DIRECTORY <dir>``
Schedule the call for the end of the given directory instead of the
current directory. The ``<dir>`` may reference either a source
directory or its corresponding binary directory. Relative paths are
treated as relative to the current source directory.
The given directory must be known to CMake, being either the top-level
directory or one added by :command:`add_subdirectory`. Furthermore,
the given directory must not yet be finished processing. This means
it can be the current directory or one of its ancestors.
``ID <id>``
Specify an identification for the deferred call.
The ``<id>`` may not be empty and may not begin with a capital letter ``A-Z``.
The ``<id>`` may begin with an underscore (``_``) only if it was generated
automatically by an earlier call that used ``ID_VAR`` to get the id.
``ID_VAR <var>``
Specify a variable in which to store the identification for the
deferred call. If ``ID <id>`` is not given, a new identification
will be generated and the generated id will start with an underscore (``_``).
The currently scheduled list of deferred calls may be retrieved:
.. code-block:: cmake
cmake_language(DEFER [DIRECTORY <dir>] GET_CALL_IDS <var>)
This will store in ``<var>`` a :ref:`semicolon-separated list <CMake Language
Lists>` of deferred call ids. The ids are for the directory scope in which
the calls have been deferred to (i.e. where they will be executed), which can
be different to the scope in which they were created. The ``DIRECTORY``
option can be used to specify the scope for which to retrieve the call ids.
If that option is not given, the call ids for the current directory scope
will be returned.
Details of a specific call may be retrieved from its id:
.. code-block:: cmake
cmake_language(DEFER [DIRECTORY <dir>] GET_CALL <id> <var>)
This will store in ``<var>`` a :ref:`semicolon-separated list <CMake Language
Lists>` in which the first element is the name of the command to be
called, and the remaining elements are its unevaluated arguments (any
contained ``;`` characters are included literally and cannot be distinguished
from multiple arguments). If multiple calls are scheduled with the same id,
this retrieves the first one. If no call is scheduled with the given id in
the specified ``DIRECTORY`` scope (or the current directory scope if no
``DIRECTORY`` option is given), this stores an empty string in the variable.
Deferred calls may be canceled by their id:
.. code-block:: cmake
cmake_language(DEFER [DIRECTORY <dir>] CANCEL_CALL <id>...)
This cancels all deferred calls matching any of the given ids in the specified
``DIRECTORY`` scope (or the current directory scope if no ``DIRECTORY`` option
is given). Unknown ids are silently ignored.
Deferred Call Examples
""""""""""""""""""""""
For example, the code:
.. code-block:: cmake
cmake_language(DEFER CALL message "${deferred_message}")
cmake_language(DEFER ID_VAR id CALL message "Canceled Message")
cmake_language(DEFER CANCEL_CALL ${id})
message("Immediate Message")
set(deferred_message "Deferred Message")
prints::
Immediate Message
Deferred Message
The ``Canceled Message`` is never printed because its command is
canceled. The ``deferred_message`` variable reference is not evaluated
until the call site, so it can be set after the deferred call is scheduled.
In order to evaluate variable references immediately when scheduling a
deferred call, wrap it using ``cmake_language(EVAL)``. However, note that
arguments will be re-evaluated in the deferred call, though that can be
avoided by using bracket arguments. For example:
.. code-block:: cmake
set(deferred_message "Deferred Message 1")
set(re_evaluated [[${deferred_message}]])
cmake_language(EVAL CODE "
cmake_language(DEFER CALL message [[${deferred_message}]])
cmake_language(DEFER CALL message \"${re_evaluated}\")
")
message("Immediate Message")
set(deferred_message "Deferred Message 2")
also prints::
Immediate Message
Deferred Message 1
Deferred Message 2
.. _dependency_providers:
Dependency Providers
^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.24
.. note:: A high-level introduction to this feature can be found in the
:ref:`Using Dependencies Guide <dependency_providers_overview>`.
.. signature::
cmake_language(SET_DEPENDENCY_PROVIDER <command>
SUPPORTED_METHODS <methods>...)
When a call is made to :command:`find_package` or
:command:`FetchContent_MakeAvailable`, the call may be forwarded to a
dependency provider which then has the opportunity to fulfill the request.
If the request is for one of the ``<methods>`` specified when the provider
was set, CMake calls the provider's ``<command>`` with a set of
method-specific arguments. If the provider does not fulfill the request,
or if the provider doesn't support the request's method, or no provider
is set, the built-in :command:`find_package` or
:command:`FetchContent_MakeAvailable` implementation is used to fulfill
the request in the usual way.
One or more of the following values can be specified for the ``<methods>``
when setting the provider:
``FIND_PACKAGE``
The provider command accepts :command:`find_package` requests.
``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
The provider command accepts :command:`FetchContent_MakeAvailable`
requests. It expects each dependency to be fed to the provider command
one at a time, not the whole list in one go.
Only one provider can be set at any point in time. If a provider is already
set when ``cmake_language(SET_DEPENDENCY_PROVIDER)`` is called, the new
provider replaces the previously set one. The specified ``<command>`` must
already exist when ``cmake_language(SET_DEPENDENCY_PROVIDER)`` is called.
As a special case, providing an empty string for the ``<command>`` and no
``<methods>`` will discard any previously set provider.
The dependency provider can only be set while processing one of the files
specified by the :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable.
Thus, dependency providers can only be set as part of the first call to
:command:`project`. Calling ``cmake_language(SET_DEPENDENCY_PROVIDER)``
outside of that context will result in an error.
.. versionadded:: 3.30
The :prop_gbl:`PROPAGATE_TOP_LEVEL_INCLUDES_TO_TRY_COMPILE` global
property can be set if the dependency provider also wants to be enabled
in whole-project calls to :command:`try_compile`.
.. note::
The choice of dependency provider should always be under the user's control.
As a convenience, a project may choose to provide a file that users can
list in their :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable, but
the use of such a file should always be the user's choice.
Provider commands
"""""""""""""""""
Providers define a single ``<command>`` to accept requests. The name of
the command should be specific to that provider, not something overly
generic that another provider might also use. This enables users to compose
different providers in their own custom provider. The recommended form is
``xxx_provide_dependency()``, where ``xxx`` is the provider-specific part
(e.g. ``vcpkg_provide_dependency()``, ``conan_provide_dependency()``,
``ourcompany_provide_dependency()``, and so on).
.. code-block:: cmake
xxx_provide_dependency(<method> [<method-specific-args>...])
Because some methods expect certain variables to be set in the calling scope,
the provider command should typically be implemented as a macro rather than a
function. This ensures it does not introduce a new variable scope.
The arguments CMake passes to the dependency provider depend on the type of
request. The first argument is always the method, and it will only ever
be one of the ``<methods>`` that was specified when setting the provider.
``FIND_PACKAGE``
The ``<method-specific-args>`` will be everything passed to the
:command:`find_package` call that requested the dependency. The first of
these ``<method-specific-args>`` will therefore always be the name of the
dependency. Dependency names are case-sensitive for this method because
:command:`find_package` treats them case-sensitively too.
If the provider command fulfills the request, it must set the same variable
that :command:`find_package` expects to be set. For a dependency named
``depName``, the provider must set ``depName_FOUND`` to true if it fulfilled
the request. If the provider returns without setting this variable, CMake
will assume the request was not fulfilled and will fall back to the
built-in implementation.
If the provider needs to call the built-in :command:`find_package`
implementation as part of its processing, it can do so by including the
``BYPASS_PROVIDER`` keyword as one of the arguments.
``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
The ``<method-specific-args>`` will be everything passed to the
:command:`FetchContent_Declare` call that corresponds to the requested
dependency, with the following exceptions:
* If ``SOURCE_DIR`` or ``BINARY_DIR`` were not part of the original
declared arguments, they will be added with their default values.
* If :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` is set to ``NEVER``,
any ``FIND_PACKAGE_ARGS`` will be omitted.
* The ``OVERRIDE_FIND_PACKAGE`` keyword is always omitted.
The first of the ``<method-specific-args>`` will always be the name of the
dependency. Dependency names are case-insensitive for this method because
:module:`FetchContent` also treats them case-insensitively.
If the provider fulfills the request, it should call
:command:`FetchContent_SetPopulated`, passing the name of the dependency as
the first argument. The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments to that
command should only be given if the provider makes the dependency's source
and build directories available in exactly the same way as the built-in
:command:`FetchContent_MakeAvailable` command.
If the provider returns without calling :command:`FetchContent_SetPopulated`
for the named dependency, CMake will assume the request was not fulfilled
and will fall back to the built-in implementation.
Note that empty arguments may be significant for this method (e.g. an empty
string following a ``GIT_SUBMODULES`` keyword). Therefore, if forwarding
these arguments on to another command, extra care must be taken to avoid such
arguments being silently dropped.
If ``FETCHCONTENT_SOURCE_DIR_<uppercaseDepName>`` is set, then the
dependency provider will never see requests for the ``<depName>`` dependency
for this method. When the user sets such a variable, they are explicitly
overriding where to get that dependency from and are taking on the
responsibility that their overriding version meets any requirements for that
dependency and is compatible with whatever else in the project uses it.
Depending on the value of :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE`
and whether the ``OVERRIDE_FIND_PACKAGE`` option was given to
:command:`FetchContent_Declare`, having
``FETCHCONTENT_SOURCE_DIR_<uppercaseDepName>`` set may also prevent the
dependency provider from seeing requests for a ``find_package(depName)``
call too.
Provider Examples
"""""""""""""""""
This first example only intercepts :command:`find_package` calls. The
provider command runs an external tool which copies the relevant artifacts
into a provider-specific directory, if that tool knows about the dependency.
It then relies on the built-in implementation to then find those artifacts.
:command:`FetchContent_MakeAvailable` calls would not go through the provider.
.. code-block:: cmake
:caption: mycomp_provider.cmake
# Always ensure we have the policy settings this provider expects
cmake_minimum_required(VERSION 3.24)
set(MYCOMP_PROVIDER_INSTALL_DIR ${CMAKE_BINARY_DIR}/mycomp_packages
CACHE PATH "The directory this provider installs packages to"
)
# Tell the built-in implementation to look in our area first, unless
# the find_package() call uses NO_..._PATH options to exclude it
list(APPEND CMAKE_MODULE_PATH ${MYCOMP_PROVIDER_INSTALL_DIR}/cmake)
list(APPEND CMAKE_PREFIX_PATH ${MYCOMP_PROVIDER_INSTALL_DIR})
macro(mycomp_provide_dependency method package_name)
execute_process(
COMMAND some_tool ${package_name} --installdir ${MYCOMP_PROVIDER_INSTALL_DIR}
COMMAND_ERROR_IS_FATAL ANY
)
endmacro()
cmake_language(
SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
SUPPORTED_METHODS FIND_PACKAGE
)
The user would then typically use the above file like so::
cmake -DCMAKE_PROJECT_TOP_LEVEL_INCLUDES=/path/to/mycomp_provider.cmake ...
The next example demonstrates a provider that accepts both methods, but
only handles one specific dependency. It enforces providing Google Test
using :module:`FetchContent`, but leaves all other dependencies to be
fulfilled by CMake's built-in implementation. It accepts a few different
names, which demonstrates one way of working around projects that hard-code
an unusual or undesirable way of adding this particular dependency to the
build. The example also demonstrates how to use the :command:`list` command
to preserve variables that may be overwritten by a call to
:command:`FetchContent_MakeAvailable`.
.. code-block:: cmake
:caption: mycomp_provider.cmake
cmake_minimum_required(VERSION 3.24)
# Because we declare this very early, it will take precedence over any
# details the project might declare later for the same thing
include(FetchContent)
FetchContent_Declare(
googletest
GIT_REPOSITORY https://github.com/google/googletest.git
GIT_TAG e2239ee6043f73722e7aa812a459f54a28552929 # release-1.11.0
)
# Both FIND_PACKAGE and FETCHCONTENT_MAKEAVAILABLE_SERIAL methods provide
# the package or dependency name as the first method-specific argument.
macro(mycomp_provide_dependency method dep_name)
if("${dep_name}" MATCHES "^(gtest|googletest)$")
# Save our current command arguments in case we are called recursively
list(APPEND mycomp_provider_args ${method} ${dep_name})
# This will forward to the built-in FetchContent implementation,
# which detects a recursive call for the same thing and avoids calling
# the provider again if dep_name is the same as the current call.
FetchContent_MakeAvailable(googletest)
# Restore our command arguments
list(POP_BACK mycomp_provider_args dep_name method)
# Tell the caller we fulfilled the request
if("${method}" STREQUAL "FIND_PACKAGE")
# We need to set this if we got here from a find_package() call
# since we used a different method to fulfill the request.
# This example assumes projects only use the gtest targets,
# not any of the variables the FindGTest module may define.
set(${dep_name}_FOUND TRUE)
elseif(NOT "${dep_name}" STREQUAL "googletest")
# We used the same method, but were given a different name to the
# one we populated with. Tell the caller about the name it used.
FetchContent_SetPopulated(${dep_name}
SOURCE_DIR "${googletest_SOURCE_DIR}"
BINARY_DIR "${googletest_BINARY_DIR}"
)
endif()
endif()
endmacro()
cmake_language(
SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
SUPPORTED_METHODS
FIND_PACKAGE
FETCHCONTENT_MAKEAVAILABLE_SERIAL
)
The final example demonstrates how to modify arguments to a
:command:`find_package` call. It forces all such calls to have the
``QUIET`` keyword. It uses the ``BYPASS_PROVIDER`` keyword to prevent
calling the provider command recursively for the same dependency.
.. code-block:: cmake
:caption: mycomp_provider.cmake
cmake_minimum_required(VERSION 3.24)
macro(mycomp_provide_dependency method)
find_package(${ARGN} BYPASS_PROVIDER QUIET)
endmacro()
cmake_language(
SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
SUPPORTED_METHODS FIND_PACKAGE
)
Getting current message log level
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.25
.. signature::
cmake_language(GET_MESSAGE_LOG_LEVEL <output_variable>)
Writes the current :command:`message` logging level
into the given ``<output_variable>``.
See :command:`message` for the possible logging levels.
The current message logging level can be set either using the
:cmake-option:`--log-level` command line option of the :manual:`cmake(1)`
program or using the :variable:`CMAKE_MESSAGE_LOG_LEVEL` variable.
If both the command line option and the variable are set, the command line
option takes precedence. If neither are set, the default logging level
is returned.
Terminating Scripts
^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.29
.. signature::
cmake_language(EXIT <exit-code>)
Terminate the current :option:`cmake -P` script and exit with ``<exit-code>``.
This command works only in :ref:`script mode <Script Processing Mode>`.
If used outside of that context, it will cause a fatal error.
The ``<exit-code>`` should be non-negative.
If ``<exit-code>`` is negative, then the behavior
is unspecified (e.g., on Windows the error code -1
becomes ``0xffffffff``, and on Linux it becomes 255).
Exit codes above 255 may not be supported by the underlying
shell or platform, and some shells may interpret values
above 125 specially. Therefore, it is advisable to only
specify an ``<exit-code>`` in the range 0 to 125.
Trace Control
^^^^^^^^^^^^^
.. versionadded:: 4.2
.. signature::
cmake_language(TRACE ON [EXPAND])
cmake_language(TRACE OFF)
:target:
TRACE
TRACE-OFF
The TRACE subcommand controls runtime tracing of executed CMake commands and
macros within the current process. When enabled, trace output is written
in the same format as if CMake had been started with the
:option:`cmake --trace` or :option:`cmake --trace-expand` command line options.
Tracing scopes are nestable. Multiple ``TRACE ON`` calls may be active at the
same time, and each ``TRACE OFF`` deactivates one nesting level.
If CMake is run with :option:`cmake --trace` or :option:`cmake --trace-expand`,
those options override and force tracing globally, regardless of
``cmake_language(TRACE OFF)`` calls. In such cases, the command may still
be invoked but has no effect on the trace state.
@@ -0,0 +1,70 @@
cmake_minimum_required
----------------------
Require a minimum version of cmake.
.. code-block:: cmake
cmake_minimum_required(VERSION <min>[...<policy_max>] [FATAL_ERROR])
.. versionadded:: 3.12
The optional ``<policy_max>`` version behavior; ignored in older CMake.
Sets the minimum required version of cmake for a project.
Also updates the policy settings as explained below.
``<min>`` and the optional ``<policy_max>`` are each CMake versions of the
form ``major.minor[.patch[.tweak]]``, and the ``...`` is literal.
If the running version of CMake is lower than the ``<min>`` required
version it will stop processing the project and report an error.
The optional ``<policy_max>`` version, if specified, must be at least the
``<min>`` version and sets the `Policy Version`_.
If the running version of CMake is older than 3.12, the extra ``...``
dots will be seen as version component separators, resulting in the
``...<policy_max>`` part being ignored and preserving the pre-3.12
behavior of basing policies on ``<min>``.
This command will set the value of the
:variable:`CMAKE_MINIMUM_REQUIRED_VERSION` variable to ``<min>``.
The ``FATAL_ERROR`` option is accepted but ignored by CMake 2.6 and
higher. It should be specified so CMake versions 2.4 and lower fail
with an error instead of just a warning.
.. note::
Call the ``cmake_minimum_required()`` command at the beginning of
the top-level ``CMakeLists.txt`` file even before calling the
:command:`project` command. It is important to establish version
and policy settings before invoking other commands whose behavior
they may affect. See also policy :policy:`CMP0000`.
Calling ``cmake_minimum_required()`` inside a :command:`function`
limits some effects to the function scope when invoked. For example,
the :variable:`CMAKE_MINIMUM_REQUIRED_VERSION` variable won't be set
in the calling scope. Functions do not introduce their own policy
scope though, so policy settings of the caller *will* be affected
(see below). Due to this mix of things that do and do not affect the
calling scope, calling ``cmake_minimum_required()`` inside a function
is generally discouraged.
.. _`Policy Version`:
Policy Version
^^^^^^^^^^^^^^
``cmake_minimum_required(VERSION <min>[...<policy_max>])`` implicitly
invokes
.. code-block:: cmake
cmake_policy(VERSION <min>[...<policy_max>])
.. include:: include/POLICY_VERSION.rst
.. include:: include/DEPRECATED_POLICY_VERSIONS.rst
See Also
^^^^^^^^
* :command:`cmake_policy`
@@ -0,0 +1,193 @@
cmake_parse_arguments
---------------------
Parse function or macro arguments.
.. code-block:: cmake
cmake_parse_arguments(<prefix> <options> <one_value_keywords>
<multi_value_keywords> <args>...)
cmake_parse_arguments(PARSE_ARGV <N> <prefix> <options>
<one_value_keywords> <multi_value_keywords>)
cmake_parse_arguments(PARSE_ARGN <prefix> <options>
<one_value_keywords> <multi_value_keywords>)
.. versionadded:: 3.5
This command is implemented natively. Previously, it has been defined in the
module :module:`CMakeParseArguments`.
This command is for use in macros or functions.
It processes the arguments given to that macro or function,
and defines a set of variables which hold the values of the
respective options.
The first signature reads arguments passed in the ``<args>...``.
This may be used in either a :command:`macro` or a :command:`function`.
.. versionadded:: 3.7
The ``PARSE_ARGV`` signature is only for use in a :command:`function`
body. In this case, the arguments that are parsed come from the
``ARGV#`` variables of the calling function. The parsing starts with
the ``<N>``-th argument, where ``<N>`` is an unsigned integer.
This allows for the values to have special characters like ``;`` in them.
.. versionadded:: 4.4
The ``PARSE_ARGN`` signature is only for use in a :command:`function`
body. This starts parsing after the last named argument of the calling
function and works exactly like ``PARSE_ARGV`` with ``<N>`` being the number
of parameters in the function definition.
The ``<options>`` argument contains all options for the respective function
or macro. These are keywords that have no value following them, like the
``OPTIONAL`` keyword of the :command:`install` command.
The ``<one_value_keywords>`` argument contains all keywords for this function
or macro which are followed by one value, like the ``DESTINATION`` keyword of
the :command:`install` command.
The ``<multi_value_keywords>`` argument contains all keywords for this
function or macro which can be followed by more than one value, like the
``TARGETS`` or ``FILES`` keywords of the :command:`install` command.
.. versionchanged:: 3.5
All keywords must be unique. Each keyword can only be specified
once in any of the ``<options>``, ``<one_value_keywords>``, or
``<multi_value_keywords>``. A warning will be emitted if uniqueness is
violated.
When done, ``cmake_parse_arguments`` will consider for each of the
keywords listed in ``<options>``, ``<one_value_keywords>``, and
``<multi_value_keywords>``, a variable composed of the given ``<prefix>``
followed by ``"_"`` and the name of the respective keyword. For
``<one_value_keywords>`` and ``<multi_value_keywords>``, these variables
will then hold the respective value(s) from the argument list, or be undefined
if the associated keyword was not given (policy :policy:`CMP0174` can also
affect the behavior for ``<one_value_keywords>``). For the ``<options>``
keywords, these variables will always be defined, and they will be set to
``TRUE`` if the keyword is present, or ``FALSE`` if it is not.
All remaining arguments are collected in a variable
``<prefix>_UNPARSED_ARGUMENTS`` that will be undefined if all arguments
were recognized. This can be checked afterwards to see
whether your macro or function was called with unrecognized parameters.
.. versionadded:: 3.15
``<one_value_keywords>`` and ``<multi_value_keywords>`` that were given no
values at all are collected in a variable
``<prefix>_KEYWORDS_MISSING_VALUES`` that will be undefined if all keywords
received values. This can be checked to see if there were keywords without
any values given.
.. versionchanged:: 3.31
If a ``<one_value_keyword>`` is followed by an empty string as its value,
policy :policy:`CMP0174` controls whether a corresponding
``<prefix>_<keyword>`` variable is defined or not.
Choose a ``<prefix>`` carefully to avoid clashing with existing variable names.
When used inside a function, it is usually suitable to use the prefix ``arg``.
There is a very strong convention that all keywords are fully uppercase, so
this prefix results in variables of the form ``arg_SOME_KEYWORD``. This makes
the code more readable, and it minimizes the chance of clashing with cache
variables, which also have a strong convention of being all uppercase.
.. code-block:: cmake
function(my_install)
set(options OPTIONAL FAST)
set(oneValueArgs DESTINATION RENAME)
set(multiValueArgs TARGETS CONFIGURATIONS)
cmake_parse_arguments(PARSE_ARGV 0 arg
"${options}" "${oneValueArgs}" "${multiValueArgs}"
)
# The above will set or unset variables with the following names:
# arg_OPTIONAL
# arg_FAST
# arg_DESTINATION
# arg_RENAME
# arg_TARGETS
# arg_CONFIGURATIONS
#
# The following will also be set or unset:
# arg_UNPARSED_ARGUMENTS
# arg_KEYWORDS_MISSING_VALUES
When used inside a macro, ``arg`` might not be a suitable prefix because the
code will affect the calling scope. If another macro also called in the same
scope were to use ``arg`` in its own call to ``cmake_parse_arguments()``,
and if there are any common keywords between the two macros, the later call's
variables can overwrite or remove those of the earlier macro's call.
Therefore, it is advisable to incorporate something unique from the macro name
in the ``<prefix>``, such as ``arg_lowercase_macro_name``.
.. code-block:: cmake
macro(my_install)
set(options OPTIONAL FAST)
set(oneValueArgs DESTINATION RENAME)
set(multiValueArgs TARGETS CONFIGURATIONS)
cmake_parse_arguments(arg_my_install
"${options}" "${oneValueArgs}" "${multiValueArgs}"
${ARGN}
)
# ...
endmacro()
macro(my_special_install)
# NOTE: Has the same keywords as my_install()
set(options OPTIONAL FAST)
set(oneValueArgs DESTINATION RENAME)
set(multiValueArgs TARGETS CONFIGURATIONS)
cmake_parse_arguments(arg_my_special_install
"${options}" "${oneValueArgs}" "${multiValueArgs}"
${ARGN}
)
# ...
endmacro()
Suppose the above macros are called one after the other, like so:
.. code-block:: cmake
my_install(TARGETS foo bar DESTINATION bin OPTIONAL blub CONFIGURATIONS)
my_special_install(TARGETS barry DESTINATION sbin RENAME FAST)
After these two calls, the following describes the variables that will be
set or unset::
arg_my_install_OPTIONAL = TRUE
arg_my_install_FAST = FALSE # was not present in call to my_install
arg_my_install_DESTINATION = "bin"
arg_my_install_RENAME <UNSET> # was not present
arg_my_install_TARGETS = "foo;bar"
arg_my_install_CONFIGURATIONS <UNSET> # was not present
arg_my_install_UNPARSED_ARGUMENTS = "blub" # nothing expected after "OPTIONAL"
arg_my_install_KEYWORDS_MISSING_VALUES = "CONFIGURATIONS" # value was missing
arg_my_special_install_OPTIONAL = FALSE # was not present
arg_my_special_install_FAST = TRUE
arg_my_special_install_DESTINATION = "sbin"
arg_my_special_install_RENAME <UNSET> # value was missing
arg_my_special_install_TARGETS = "barry"
arg_my_special_install_CONFIGURATIONS <UNSET> # was not present
arg_my_special_install_UNPARSED_ARGUMENTS <UNSET>
arg_my_special_install_KEYWORDS_MISSING_VALUES = "RENAME"
Keywords terminate lists of values. If a keyword is given directly after a
``<one_value_keyword>``, that preceding ``<one_value_keyword>`` receives no
value and the keyword is added to the ``<prefix>_KEYWORDS_MISSING_VALUES``
variable. In the above example, the call to ``my_special_install()`` contains
the ``RENAME`` keyword immediately followed by the ``FAST`` keyword.
In this case, ``FAST`` terminates processing of the ``RENAME`` keyword.
``arg_my_special_install_FAST`` is set to ``TRUE``,
``arg_my_special_install_RENAME`` is unset, and
``arg_my_special_install_KEYWORDS_MISSING_VALUES`` contains the value
``RENAME``.
See Also
^^^^^^^^
* :command:`function`
* :command:`macro`
@@ -0,0 +1,784 @@
cmake_path
----------
.. versionadded:: 3.20
This command is for the manipulation of paths. Only syntactic aspects of
paths are handled, there is no interaction of any kind with any underlying
file system. The path may represent a non-existing path or even one that
is not allowed to exist on the current file system or platform.
For operations that do interact with the filesystem, see the :command:`file`
command.
.. note::
The ``cmake_path`` command handles paths in the format of the build system
(i.e. the host platform), not the target system. When cross-compiling,
if the path contains elements that are not representable on the host
platform (e.g. a drive letter when the host is not Windows), the results
will be unpredictable.
Synopsis
^^^^^^^^
.. parsed-literal::
`Conventions`_
`Path Structure And Terminology`_
`Normalization`_
`Decomposition`_
cmake_path(`GET`_ <path-var> `ROOT_NAME <GET ... ROOT_NAME_>`_ <out-var>)
cmake_path(`GET`_ <path-var> `ROOT_DIRECTORY <GET ... ROOT_DIRECTORY_>`_ <out-var>)
cmake_path(`GET`_ <path-var> `ROOT_PATH <GET ... ROOT_PATH_>`_ <out-var>)
cmake_path(`GET`_ <path-var> `FILENAME <GET ... FILENAME_>`_ <out-var>)
cmake_path(`GET`_ <path-var> `EXTENSION <GET ... EXTENSION_>`_ [LAST_ONLY] <out-var>)
cmake_path(`GET`_ <path-var> `STEM <GET ... STEM_>`_ [LAST_ONLY] <out-var>)
cmake_path(`GET`_ <path-var> `RELATIVE_PART <GET ... RELATIVE_PART_>`_ <out-var>)
cmake_path(`GET`_ <path-var> `PARENT_PATH <GET ... PARENT_PATH_>`_ <out-var>)
`Query`_
cmake_path(`HAS_ROOT_NAME`_ <path-var> <out-var>)
cmake_path(`HAS_ROOT_DIRECTORY`_ <path-var> <out-var>)
cmake_path(`HAS_ROOT_PATH`_ <path-var> <out-var>)
cmake_path(`HAS_FILENAME`_ <path-var> <out-var>)
cmake_path(`HAS_EXTENSION`_ <path-var> <out-var>)
cmake_path(`HAS_STEM`_ <path-var> <out-var>)
cmake_path(`HAS_RELATIVE_PART`_ <path-var> <out-var>)
cmake_path(`HAS_PARENT_PATH`_ <path-var> <out-var>)
cmake_path(`IS_ABSOLUTE`_ <path-var> <out-var>)
cmake_path(`IS_RELATIVE`_ <path-var> <out-var>)
cmake_path(`IS_PREFIX`_ <path-var> <input> [NORMALIZE] <out-var>)
`Comparison`_
cmake_path(`COMPARE`_ <input1> <op> <input2> <out-var>)
`Modification`_
cmake_path(`SET`_ <path-var> [NORMALIZE] <input>)
cmake_path(`APPEND`_ <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
cmake_path(`APPEND_STRING`_ <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
cmake_path(`REMOVE_FILENAME`_ <path-var> [OUTPUT_VARIABLE <out-var>])
cmake_path(`REPLACE_FILENAME`_ <path-var> <input> [OUTPUT_VARIABLE <out-var>])
cmake_path(`REMOVE_EXTENSION`_ <path-var> [LAST_ONLY] [OUTPUT_VARIABLE <out-var>])
cmake_path(`REPLACE_EXTENSION`_ <path-var> [LAST_ONLY] <input> [OUTPUT_VARIABLE <out-var>])
`Generation`_
cmake_path(`NORMAL_PATH`_ <path-var> [OUTPUT_VARIABLE <out-var>])
cmake_path(`RELATIVE_PATH`_ <path-var> [BASE_DIRECTORY <input>] [OUTPUT_VARIABLE <out-var>])
cmake_path(`ABSOLUTE_PATH`_ <path-var> [BASE_DIRECTORY <input>] [NORMALIZE] [OUTPUT_VARIABLE <out-var>])
`Native Conversion`_
cmake_path(`NATIVE_PATH`_ <path-var> [NORMALIZE] <out-var>)
cmake_path(`CONVERT`_ <input> `TO_CMAKE_PATH_LIST <CONVERT ... TO_CMAKE_PATH_LIST_>`_ <out-var> [NORMALIZE])
cmake_path(`CONVERT`_ <input> `TO_NATIVE_PATH_LIST <CONVERT ... TO_NATIVE_PATH_LIST_>`_ <out-var> [NORMALIZE])
`Hashing`_
cmake_path(`HASH`_ <path-var> <out-var>)
Conventions
^^^^^^^^^^^
The following conventions are used in this command's documentation:
``<path-var>``
Always the name of a variable. For commands that expect a ``<path-var>``
as input, the variable must exist and it is expected to hold a single path.
``<input>``
A string literal which may contain a path, path fragment, or multiple paths
with a special separator depending on the command. See the description of
each command to see how this is interpreted.
``<input>...``
Zero or more string literal arguments.
``<out-var>``
The name of a variable into which the result of a command will be written.
.. _Path Structure And Terminology:
Path Structure And Terminology
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
A path has the following structure (all components are optional, with some
constraints):
::
root-name root-directory-separator (item-name directory-separator)* filename
``root-name``
Identifies the root on a filesystem with multiple roots (such as ``"C:"``
or ``"//myserver"``). It is optional.
``root-directory-separator``
A directory separator that, if present, indicates that this path is
absolute. If it is missing and the first element other than the
``root-name`` is an ``item-name``, then the path is relative.
``item-name``
A sequence of characters that aren't directory separators. This name may
identify a file, a hard link, a symbolic link, or a directory. Two special
cases are recognized:
* The item name consisting of a single dot character ``.`` is a
directory name that refers to the current directory.
* The item name consisting of two dot characters ``..`` is a
directory name that refers to the parent directory.
The ``(...)*`` pattern shown above is to indicate that there can be zero
or more item names, with multiple items separated by a
``directory-separator``. The ``()*`` characters are not part of the path.
``directory-separator``
The only recognized directory separator is a forward slash character ``/``.
If this character is repeated, it is treated as a single directory
separator. In other words, ``/usr///////lib`` is the same as ``/usr/lib``.
.. _FILENAME_DEF:
.. _EXTENSION_DEF:
.. _STEM_DEF:
``filename``
A path has a ``filename`` if it does not end with a ``directory-separator``.
The ``filename`` is effectively the last ``item-name`` of the path, so it
can also be a hard link, symbolic link or a directory.
A ``filename`` can have an *extension*. By default, the extension is
defined as the sub-string beginning at the left-most period (including
the period) and until the end of the ``filename``. In commands that
accept a ``LAST_ONLY`` keyword, ``LAST_ONLY`` changes the interpretation
to the sub-string beginning at the right-most period.
The following exceptions apply to the above interpretation:
* If the first character in the ``filename`` is a period, that period is
ignored (i.e. a ``filename`` like ``".profile"`` is treated as having
no extension).
* If the ``filename`` is either ``.`` or ``..``, it has no extension.
The *stem* is the part of the ``filename`` before the extension.
Some commands refer to a ``root-path``. This is the concatenation of
``root-name`` and ``root-directory-separator``, either or both of which can
be empty. A ``relative-part`` refers to the full path with any ``root-path``
removed.
.. _Creating a Path Variable:
Creating A Path Variable
^^^^^^^^^^^^^^^^^^^^^^^^
While a path can be created with care using an ordinary :command:`set`
command, it is recommended to use :command:`cmake_path(SET)` instead, as it
automatically converts the path to the required form where required. The
:command:`cmake_path(APPEND)` subcommand may be another suitable alternative
where a path needs to be constructed by joining fragments. The following
example compares the three methods for constructing the same path:
.. code-block:: cmake
set(path1 "${CMAKE_CURRENT_SOURCE_DIR}/data")
cmake_path(SET path2 "${CMAKE_CURRENT_SOURCE_DIR}/data")
cmake_path(APPEND path3 "${CMAKE_CURRENT_SOURCE_DIR}" "data")
`Modification`_ and `Generation`_ sub-commands can either store the result
in-place, or in a separate variable named after an ``OUTPUT_VARIABLE``
keyword. All other sub-commands store the result in a mandatory ``<out-var>``
variable.
.. note::
The ``cmake_path`` command can be used directly with variables provided by
CMake representing paths (e.g., :variable:`CMAKE_SOURCE_DIR`). However, since
the command can modify these variables, and many of them have undefined
behavior when modified, they should never be specified as an ``<out-var>``,
and only as the ``<path-var>`` when a separate ``<out-var>`` is specified.
See :manual:`cmake-variables(7)` for the list of CMake variables and
identifiers reserved by CMake.
.. _Normalization:
Normalization
^^^^^^^^^^^^^
Some sub-commands support *normalizing* a path. The algorithm used to
normalize a path is as follows:
1. If the path is empty, stop (the normalized form of an empty path is
also an empty path).
2. Replace each ``directory-separator``, which may consist of multiple
separators, with a single ``/`` (``/a///b --> /a/b``).
3. Remove each solitary period (``.``) and any immediately following
``directory-separator`` (``/a/./b/. --> /a/b``).
4. Remove each ``item-name`` (other than ``..``) that is immediately
followed by a ``directory-separator`` and a ``..``, along with any
immediately following ``directory-separator`` (``/a/b/../c --> a/c``).
5. If there is a ``root-directory``, remove any ``..`` and any
``directory-separators`` immediately following them. The parent of the
root directory is treated as still the root directory (``/../a --> /a``).
6. If the last ``item-name`` is ``..``, remove any trailing
``directory-separator`` (``../ --> ..``).
7. If the path is empty by this stage, add a ``dot`` (normal form of ``./``
is ``.``).
.. _Path Decomposition:
Decomposition
^^^^^^^^^^^^^
.. _GET:
The following forms of the ``GET`` subcommand each retrieve a different
component or group of components from a path. See
`Path Structure And Terminology`_ for the meaning of each path component.
.. signature::
cmake_path(GET <path-var> ROOT_NAME <out-var>)
cmake_path(GET <path-var> ROOT_DIRECTORY <out-var>)
cmake_path(GET <path-var> ROOT_PATH <out-var>)
cmake_path(GET <path-var> FILENAME <out-var>)
cmake_path(GET <path-var> EXTENSION [LAST_ONLY] <out-var>)
cmake_path(GET <path-var> STEM [LAST_ONLY] <out-var>)
cmake_path(GET <path-var> RELATIVE_PART <out-var>)
cmake_path(GET <path-var> PARENT_PATH <out-var>)
:target:
GET ... ROOT_NAME
GET ... ROOT_DIRECTORY
GET ... ROOT_PATH
GET ... FILENAME
GET ... EXTENSION
GET ... STEM
GET ... RELATIVE_PART
GET ... PARENT_PATH
If a requested component is not present in the path, an empty string will be
stored in ``<out-var>``. For example, only Windows systems have the concept
of a ``root-name``, so when the host machine is non-Windows, the ``ROOT_NAME``
subcommand will always return an empty string.
For ``PARENT_PATH``, if the :cref:`HAS_RELATIVE_PART` sub-command returns
false, the result is a copy of ``<path-var>``. Note that this implies that a
root directory is considered to have a parent, with that parent being itself.
Where :cref:`HAS_RELATIVE_PART` returns true, the result will essentially be
``<path-var>`` with one less element.
Root examples
"""""""""""""
.. code-block:: cmake
set(path "c:/a")
cmake_path(GET path ROOT_NAME rootName)
cmake_path(GET path ROOT_DIRECTORY rootDir)
cmake_path(GET path ROOT_PATH rootPath)
message("Root name is \"${rootName}\"")
message("Root directory is \"${rootDir}\"")
message("Root path is \"${rootPath}\"")
::
Root name is "c:"
Root directory is "/"
Root path is "c:/"
Filename examples
"""""""""""""""""
.. code-block:: cmake
set(path "/a/b")
cmake_path(GET path FILENAME filename)
message("First filename is \"${filename}\"")
# Trailing slash means filename is empty
set(path "/a/b/")
cmake_path(GET path FILENAME filename)
message("Second filename is \"${filename}\"")
::
First filename is "b"
Second filename is ""
Extension and stem examples
"""""""""""""""""""""""""""
.. code-block:: cmake
set(path "name.ext1.ext2")
cmake_path(GET path EXTENSION fullExt)
cmake_path(GET path STEM fullStem)
message("Full extension is \"${fullExt}\"")
message("Full stem is \"${fullStem}\"")
# Effect of LAST_ONLY
cmake_path(GET path EXTENSION LAST_ONLY lastExt)
cmake_path(GET path STEM LAST_ONLY lastStem)
message("Last extension is \"${lastExt}\"")
message("Last stem is \"${lastStem}\"")
# Special cases
set(dotPath "/a/.")
set(dotDotPath "/a/..")
set(someMorePath "/a/.some.more")
cmake_path(GET dotPath EXTENSION dotExt)
cmake_path(GET dotPath STEM dotStem)
cmake_path(GET dotDotPath EXTENSION dotDotExt)
cmake_path(GET dotDotPath STEM dotDotStem)
cmake_path(GET someMorePath EXTENSION someMoreExt)
cmake_path(GET someMorePath STEM someMoreStem)
message("Dot extension is \"${dotExt}\"")
message("Dot stem is \"${dotStem}\"")
message("Dot-dot extension is \"${dotDotExt}\"")
message("Dot-dot stem is \"${dotDotStem}\"")
message(".some.more extension is \"${someMoreExt}\"")
message(".some.more stem is \"${someMoreStem}\"")
::
Full extension is ".ext1.ext2"
Full stem is "name"
Last extension is ".ext2"
Last stem is "name.ext1"
Dot extension is ""
Dot stem is "."
Dot-dot extension is ""
Dot-dot stem is ".."
.some.more extension is ".more"
.some.more stem is ".some"
Relative part examples
""""""""""""""""""""""
.. code-block:: cmake
set(path "c:/a/b")
cmake_path(GET path RELATIVE_PART result)
message("Relative part is \"${result}\"")
set(path "c/d")
cmake_path(GET path RELATIVE_PART result)
message("Relative part is \"${result}\"")
set(path "/")
cmake_path(GET path RELATIVE_PART result)
message("Relative part is \"${result}\"")
::
Relative part is "a/b"
Relative part is "c/d"
Relative part is ""
Path traversal examples
"""""""""""""""""""""""
.. code-block:: cmake
set(path "c:/a/b")
cmake_path(GET path PARENT_PATH result)
message("Parent path is \"${result}\"")
set(path "c:/")
cmake_path(GET path PARENT_PATH result)
message("Parent path is \"${result}\"")
::
Parent path is "c:/a"
Parent path is "c:/"
.. _Path Query:
Query
^^^^^
Each of the :cref:`GET` subcommands has a corresponding
``HAS_...`` subcommand which can be used to discover whether a particular path
component is present. See `Path Structure And Terminology`_ for the
meaning of each path component.
.. signature::
cmake_path(HAS_ROOT_NAME <path-var> <out-var>)
cmake_path(HAS_ROOT_DIRECTORY <path-var> <out-var>)
cmake_path(HAS_ROOT_PATH <path-var> <out-var>)
cmake_path(HAS_FILENAME <path-var> <out-var>)
cmake_path(HAS_EXTENSION <path-var> <out-var>)
cmake_path(HAS_STEM <path-var> <out-var>)
cmake_path(HAS_RELATIVE_PART <path-var> <out-var>)
cmake_path(HAS_PARENT_PATH <path-var> <out-var>)
Each of the above follows the predictable pattern of setting ``<out-var>``
to true if the path has the associated component, or false otherwise.
Note the following special cases:
* For ``HAS_ROOT_PATH``, a true result will only be returned if at least one
of ``root-name`` or ``root-directory`` is non-empty.
* For ``HAS_PARENT_PATH``, the root directory is also considered to have a
parent, which will be itself. The result is true except if the path
consists of just a :ref:`filename <FILENAME_DEF>`.
.. signature::
cmake_path(IS_ABSOLUTE <path-var> <out-var>)
Sets ``<out-var>`` to true if ``<path-var>`` is absolute. An absolute path
is a path that unambiguously identifies the location of a file without
reference to an additional starting location. On Windows, this means the
path must have both a ``root-name`` and a ``root-directory-separator`` to be
considered absolute. On other platforms, just a ``root-directory-separator``
is sufficient. Note that this means on Windows, ``IS_ABSOLUTE`` can be
false while :cref:`HAS_ROOT_DIRECTORY` can be true.
.. signature::
cmake_path(IS_RELATIVE <path-var> <out-var>)
This will store the opposite of :cref:`IS_ABSOLUTE` in ``<out-var>``.
.. signature::
cmake_path(IS_PREFIX <path-var> <input> [NORMALIZE] <out-var>)
Checks if ``<path-var>`` is the prefix of ``<input>``.
When the ``NORMALIZE`` option is specified, ``<path-var>`` and ``<input>``
are :ref:`normalized <Normalization>` before the check.
.. code-block:: cmake
set(path "/a/b/c")
cmake_path(IS_PREFIX path "/a/b/c/d" result) # result = true
cmake_path(IS_PREFIX path "/a/b" result) # result = false
cmake_path(IS_PREFIX path "/x/y/z" result) # result = false
set(path "/a/b")
cmake_path(IS_PREFIX path "/a/c/../b" NORMALIZE result) # result = true
.. _Path Comparison:
Comparison
^^^^^^^^^^
.. _COMPARE:
.. signature::
cmake_path(COMPARE <input1> EQUAL <input2> <out-var>)
cmake_path(COMPARE <input1> NOT_EQUAL <input2> <out-var>)
:target:
COMPARE ... EQUAL
COMPARE ... NOT_EQUAL
Compares the lexical representations of two paths provided as string literals.
No normalization is performed on either path, except multiple consecutive
directory separators are effectively collapsed into a single separator.
Equality is determined according to the following pseudo-code logic:
::
if(NOT <input1>.root_name() STREQUAL <input2>.root_name())
return FALSE
if(<input1>.has_root_directory() XOR <input2>.has_root_directory())
return FALSE
Return FALSE if a relative portion of <input1> is not lexicographically
equal to the relative portion of <input2>. This comparison is performed path
component-wise. If all of the components compare equal, then return TRUE.
.. note::
Unlike most other ``cmake_path()`` subcommands, the ``COMPARE`` subcommand
takes literal strings as input, not the names of variables.
.. _Path Modification:
Modification
^^^^^^^^^^^^
.. signature::
cmake_path(SET <path-var> [NORMALIZE] <input>)
Assigns the ``<input>`` path to ``<path-var>``. If ``<input>`` is a native
path, it is converted into a CMake-style path with forward-slashes
(``/``). On Windows, the long filename marker is taken into account.
When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` after the conversion.
For example:
.. code-block:: cmake
set(native_path "c:\\a\\b/..\\c")
cmake_path(SET path "${native_path}")
message("CMake path is \"${path}\"")
cmake_path(SET path NORMALIZE "${native_path}")
message("Normalized CMake path is \"${path}\"")
Output::
CMake path is "c:/a/b/../c"
Normalized CMake path is "c:/a/c"
.. signature::
cmake_path(APPEND <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
Appends all the ``<input>`` arguments to the ``<path-var>`` using ``/`` as
the ``directory-separator``. Depending on the ``<input>``, the previous
contents of ``<path-var>`` may be discarded. For each ``<input>`` argument,
the following algorithm (pseudo-code) applies:
::
# <path> is the contents of <path-var>
if(<input>.is_absolute() OR
(<input>.has_root_name() AND
NOT <input>.root_name() STREQUAL <path>.root_name()))
replace <path> with <input>
return()
endif()
if(<input>.has_root_directory())
remove any root-directory and the entire relative path from <path>
elseif(<path>.has_filename() OR
(NOT <path-var>.has_root_directory() OR <path>.is_absolute()))
append directory-separator to <path>
endif()
append <input> omitting any root-name to <path>
See :ref:`Creating a Path Variable` for details on the output variable.
.. signature::
cmake_path(APPEND_STRING <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
Appends all the ``<input>`` arguments to the ``<path-var>`` without adding any
``directory-separator``.
See :ref:`Creating a Path Variable` for details on the output variable.
.. signature::
cmake_path(REMOVE_FILENAME <path-var> [OUTPUT_VARIABLE <out-var>])
Removes the :ref:`filename <FILENAME_DEF>` component (as returned by
:cref:`GET ... FILENAME`) from ``<path-var>``. After removal, any trailing
``directory-separator`` is left alone, if present.
:cref:`HAS_FILENAME` will return false for the result, whether stored in
``<out-var>`` or ``<path-var>``.
For example:
.. code-block:: cmake
set(path "/a/b")
cmake_path(REMOVE_FILENAME path)
message("First path is \"${path}\"")
# filename is now already empty, the following removes nothing
cmake_path(REMOVE_FILENAME path)
message("Second path is \"${path}\"")
Output::
First path is "/a/"
Second path is "/a/"
See :ref:`Creating a Path Variable` for details on the output variable.
.. signature::
cmake_path(REPLACE_FILENAME <path-var> <input> [OUTPUT_VARIABLE <out-var>])
Replaces the :ref:`filename <FILENAME_DEF>` component from ``<path-var>``
with ``<input>``. If ``<path-var>`` has no filename component (i.e.
:cref:`HAS_FILENAME` returns false), the path is unchanged. The operation is
equivalent to the following:
.. code-block:: cmake
cmake_path(HAS_FILENAME path has_filename)
if(has_filename)
cmake_path(REMOVE_FILENAME path)
cmake_path(APPEND path "${input}")
endif()
See :ref:`Creating a Path Variable` for details on the output variable.
.. signature::
cmake_path(REMOVE_EXTENSION <path-var> [LAST_ONLY]
[OUTPUT_VARIABLE <out-var>])
Removes the :ref:`extension <EXTENSION_DEF>`, if any, from ``<path-var>``.
See :ref:`Creating a Path Variable` for details on the output variable.
.. signature::
cmake_path(REPLACE_EXTENSION <path-var> [LAST_ONLY] <input>
[OUTPUT_VARIABLE <out-var>])
Replaces the :ref:`extension <EXTENSION_DEF>` with ``<input>``. Its effect
is equivalent to the following:
.. code-block:: cmake
cmake_path(REMOVE_EXTENSION path)
if(NOT input MATCHES "^\\.")
cmake_path(APPEND_STRING path ".")
endif()
cmake_path(APPEND_STRING path "${input}")
See :ref:`Creating a Path Variable` for details on the output variable.
.. _Path Generation:
Generation
^^^^^^^^^^
.. signature::
cmake_path(NORMAL_PATH <path-var> [OUTPUT_VARIABLE <out-var>])
Normalizes ``<path-var>`` according the steps described in
:ref:`Normalization`.
See :ref:`Creating a Path Variable` for details on the output variable.
.. signature::
cmake_path(RELATIVE_PATH <path-var> [BASE_DIRECTORY <input>]
[OUTPUT_VARIABLE <out-var>])
Modifies ``<path-var>`` to make it relative to the ``BASE_DIRECTORY`` argument.
If ``BASE_DIRECTORY`` is not specified, the default base directory will be
:variable:`CMAKE_CURRENT_SOURCE_DIR`.
For reference, the algorithm used to compute the relative path is the same
as that used by C++
`std::filesystem::path::lexically_relative
<https://en.cppreference.com/cpp/filesystem/path/lexically_normal>`_.
See :ref:`Creating a Path Variable` for details on the output variable.
.. signature::
cmake_path(ABSOLUTE_PATH <path-var> [BASE_DIRECTORY <input>] [NORMALIZE]
[OUTPUT_VARIABLE <out-var>])
If ``<path-var>`` is a relative path (:cref:`IS_RELATIVE` is true), it is
evaluated relative to the given base directory specified by ``BASE_DIRECTORY``
option. If ``BASE_DIRECTORY`` is not specified, the default base directory
will be :variable:`CMAKE_CURRENT_SOURCE_DIR`.
When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` after the path computation.
Because ``cmake_path()`` does not access the filesystem, symbolic links are
not resolved and any leading tilde is not expanded. To compute a real path
with symbolic links resolved and leading tildes expanded, use the
:command:`file(REAL_PATH)` command instead.
See :ref:`Creating a Path Variable` for details on the output variable.
Native Conversion
^^^^^^^^^^^^^^^^^
For commands in this section, *native* refers to the host platform, not the
target platform when cross-compiling.
.. signature::
cmake_path(NATIVE_PATH <path-var> [NORMALIZE] <out-var>)
Converts a CMake-style ``<path-var>`` into a native path with
platform-specific slashes (``\`` on Windows hosts and ``/`` elsewhere).
When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` before the conversion.
See :ref:`Creating a Path Variable` for details on the output variable.
.. _CONVERT:
.. signature::
cmake_path(CONVERT <input> TO_CMAKE_PATH_LIST <out-var> [NORMALIZE])
:target:
CONVERT ... TO_CMAKE_PATH_LIST
Converts a native ``<input>`` path into a CMake-style path with forward
slashes (``/``).
On Windows hosts, the long filename marker is taken into
account. The input can be a single path or a system search path like
``$ENV{PATH}``. A search path will be converted to a
:ref:`semicolon-separated list <CMake Language Lists>` (on non-Windows
platforms, this essentially means ``:`` separators are replaced with ``;``).
When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` before the conversion.
See :ref:`Creating a Path Variable` for details on the output variable.
.. note::
Unlike most other ``cmake_path()`` subcommands, the ``CONVERT`` subcommand
takes a literal string as input, not the name of a variable.
.. signature::
cmake_path(CONVERT <input> TO_NATIVE_PATH_LIST <out-var> [NORMALIZE])
:target:
CONVERT ... TO_NATIVE_PATH_LIST
Converts a CMake-style ``<input>`` path into a native path with
platform-specific slashes (``\`` on Windows hosts and ``/`` elsewhere).
The input can be a single path or a :ref:`semicolon-separated list
<CMake Language Lists>`. A list will be converted into a native search path
(``;``-separated on Windows, ``:``-separated on other platforms).
When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` before the conversion.
See :ref:`Creating a Path Variable` for details on the output variable.
.. note::
Unlike most other ``cmake_path()`` subcommands, the ``CONVERT`` subcommand
takes a literal string as input, not the name of a variable.
For example:
.. code-block:: cmake
set(paths "/a/b/c" "/x/y/z")
cmake_path(CONVERT "${paths}" TO_NATIVE_PATH_LIST native_paths)
message("Native path list is \"${native_paths}\"")
Output on Windows::
Native path list is "\a\b\c;\x\y\z"
Output on all other platforms::
Native path list is "/a/b/c:/x/y/z"
Hashing
^^^^^^^
.. signature::
cmake_path(HASH <path-var> <out-var>)
Computes a hash value of ``<path-var>`` such that for two paths ``p1`` and
``p2`` that compare equal (:cref:`COMPARE ... EQUAL`), the hash value of
``p1`` is equal to the hash value of ``p2``. The path is always
:ref:`normalized <Normalization>` before the hash is computed.
See :ref:`Creating a Path Variable` for details on the output variable.
@@ -0,0 +1,370 @@
cmake_pkg_config
----------------
.. versionadded:: 3.31
.. only:: html
.. contents::
Process pkg-config format package files.
Synopsis
^^^^^^^^
.. parsed-literal::
cmake_pkg_config(`EXTRACT`_ <package> [<version>] [...])
cmake_pkg_config(`POPULATE`_ <package> [<version>] [...])
cmake_pkg_config(`IMPORT`_ <package> [<version>] [...])
Introduction
^^^^^^^^^^^^
This command generates CMake variables and targets from pkg-config format
package files natively, without needing to invoke or even require the presence
of a pkg-config implementation. A ``<package>`` is either an absolute path to a
package file, or a package name to be searched for using the typical pkg-config
search patterns. The optional ``<version>`` string has the same format and
semantics as a pkg-config style version specifier, with the exception that if
no comparison operator is specified ``=`` is assumed.
PkgConfig Targets
^^^^^^^^^^^^^^^^^
``cmake_pkg_config`` may recursively generate target-like names in the global
scope in order to resolve a package ``IMPORT`` or ``POPULATE`` command. These
names take the form of ``@foreign_pkgcfg::[<prefix>_]<package>`` and are exposed
via the :prop_tgt:`INTERFACE_LINK_LIBRARIES` target property of an
``IMPORT``-generated target.
It is not possible to modify or address these pkg-config native targets via
normal target-based commands. Limited control over their generation is possible
via the ``POPULATE`` command, but modification should generally be performed
inside the corresponding package file, not downstream in CMake.
Pkg-config targets are reused across commands. Once a given package name has
been resolved via ``POPULATE`` or ``IMPORT`` (but not ``EXTRACT``), all future
requests for the corresponding package name by those commands will resolve to
the previously generated pkg-config target.
``EXTRACT`` always performs the complete package name lookup in order to allow
searches for multiple installations of the same package in custom dependency
management schemes.
Common Options
^^^^^^^^^^^^^^
There are multiple signatures for this command, and some of the options are
common between them. They are:
``EXACT`` / ``QUIET`` / ``REQUIRED``
The ``EXACT`` option requests that the version string be matched exactly
(including empty string, if no version is provided), overriding the typical
pkg-config version comparison algorithm. This will ignore any comparison
operator attached to the version string.
The ``QUIET`` option disables informational messages, including those
indicating that the package cannot be found if it is not ``REQUIRED``. The
``REQUIRED`` option stops processing with an error message if the package
cannot be found.
``STRICTNESS <mode>``
Specify how strictly the contents of the package files will be verified during
parsing and resolution. An invalid file, under the provided strictness mode,
will cause the command to fail. Possible modes are:
* ``STRICT``: Closely mirrors the behavior of the original FDO pkg-config.
Variables and keywords must be unique. Variables must be defined before
they are used. The Name, Description, and Version keywords must be present.
The overall structure of the file must be valid and parsable.
* ``PERMISSIVE``: Closely mirrors the behavior of the pkgconf implementation.
Duplicate variables are overridden. Duplicate keywords are appended.
Undefined variables resolve to empty strings. The Name, Description, and
Version keywords must be present. The overall structure of the file must be
valid and parsable.
* ``BEST_EFFORT``: Same behavior as ``PERMISSIVE`` with regards to duplicate
or uninitialized variables and keywords, but will not fail under any
conditions. Package files which require BEST_EFFORT will fail validation
under all other major implementations and should be fixed.
The default strictness is ``PERMISSIVE``.
``ENV_MODE``
Specifies which environment variables will be queried when running a given
command. Possible modes are:
* ``FDO``: Queries only the original set of ``PKG_CONFIG_*`` environment
variables used by the freedesktop.org ``pkg-config`` implementation.
* ``PKGCONF``: Queries the more extensive set of environment variables used
by the ``pkgconf`` implementation.
* ``IGNORE``: Ignores the presence, absence, and value of environment
variables entirely. In all cases an environment variable would be queried
its treated as defined, but with a value of empty string for the purpose
of the operation. This does not modify the current environment. For boolean
environment variables, such as ``PKG_CONFIG_ALLOW_*``, this means they are
evaluated as truthy.
``PKG_CONFIG_SYSROOT_PATH`` is a minor exception. When ``ENV_MODE IGNORE``
is used, no root path prepending will occur by default and ``pc_sysrootdir``
remains defaulted to ``/``.
Target-generating subcommands always ignore flag-filtering environment
variables. The default environment mode is ``PKGCONF``.
``PC_LIBDIR <path>...``
Overrides the default search location for package files; also used to derive
the ``pc_path`` package variable.
When this option is not provided, the default library directory is the first
available of the following values:
#. ``CMAKE_PKG_CONFIG_PC_LIB_DIRS``
#. The ``PKG_CONFIG_LIBDIR`` environment variable
#. The output of ``pkg-config --variable pc_path pkg-config``
#. A platform-dependent default value
``PC_PATH <path>...``
Overrides the supplemental package file directories which will be prepended
to the search path; also used to derive the ``pc_path`` package variable.
When this option is not provided, the default paths are the first available of
the following values:
#. ``CMAKE_PKG_CONFIG_PC_PATH``
#. The ``PKG_CONFIG_PATH`` environment variable
#. Empty list
``DISABLE_UNINSTALLED <bool>``
Overrides the search behavior for "uninstalled" package files. These are
package files with an "-uninstalled" suffix which describe packages integrated
directly from a build tree.
Normally such package files have higher priority than "installed" packages.
When ``DISABLE_UNINSTALLED`` is true, searching for "uninstalled" packages
is disabled.
When this option is not provided, the default search behavior is determined
by the first available of the following values:
#. ``CMAKE_PKG_CONFIG_DISABLE_UNINSTALLED``
#. If the ``PKG_CONFIG_DISABLE_UNINSTALLED`` environment variable is defined
the search is disabled, otherwise it is enabled.
``PC_SYSROOT_DIR <path>``
Overrides the root path which will be prepended to paths specified by ``-I``
compile flags and ``-L`` library search locations; also used to derive the
``pc_sysrootdir`` package variable.
When this option is not provided, the default root path is provided by the
first available of the following values:
#. ``CMAKE_PKG_CONFIG_SYSROOT_DIR``
#. The ``PKG_CONFIG_SYSROOT_DIR`` environment variable
#. If no root path is available, nothing will be prepended to include or
library directory paths and ``pc_sysrootdir`` will be set to ``/``
``TOP_BUILD_DIR <path>``
Overrides the top build directory path used to derive the ``pc_top_builddir``
package variable.
When this option is not provided, the default top build directory path is
the first available of the following values:
#. ``CMAKE_PKG_CONFIG_TOP_BUILD_DIR``
#. The ``PKG_CONFIG_TOP_BUILD_DIR`` environment variable
#. If no top build directory path is available, the ``pc_top_builddir``
package variable is not set
``PREFIX <name>``
Specifying a prefix creates an independent collection of pkg-config targets
separate from previously populated targets. This enables multiple version of
a given package to co-exist, for example packages from different sysroots.
The default prefix is an empty string.
``BIND_PC_REQUIRES <<name>=<target>>...``
A list of ``<name>=<target>`` pairs, the ``name`` is a package name as it
appears in the ``Requires`` list of a pkg-config file and the ``target`` is a
CMake-native target name (not a pkg-config target).
When a given package name appears in the ``Requires`` list of a package, it
will be fulfilled with the associated CMake target. This behavior applies to
all dependencies in the pkg-config graph that have not been previously
populated.
Signatures
^^^^^^^^^^
.. signature::
cmake_pkg_config(EXTRACT <package> [<version>] [...])
.. versionadded:: 3.31
Extract the contents of the package into variables.
.. code-block:: cmake
cmake_pkg_config(EXTRACT <package> [<version>]
[REQUIRED] [EXACT] [QUIET]
[SYSTEM_INCLUDE_DIRS <path>...]
[SYSTEM_LIBRARY_DIRS <path>...]
[ALLOW_SYSTEM_INCLUDES <bool>]
[ALLOW_SYSTEM_LIBS <bool>]
[STRICTNESS <mode>]
[ENV_MODE <mode>]
[PC_LIBDIR <path>...]
[PC_PATH <path>...]
[DISABLE_UNINSTALLED <bool>]
[PC_SYSROOT_DIR <path>]
[TOP_BUILD_DIR <path>])
The following variables will be populated from the contents of package file:
==================================== ====== ========================================================================================
Variable Type Definition
==================================== ====== ========================================================================================
``CMAKE_PKG_CONFIG_NAME`` String Value of the ``Name`` keyword
``CMAKE_PKG_CONFIG_DESCRIPTION`` String Value of the ``Description`` keyword
``CMAKE_PKG_CONFIG_VERSION`` String Value of the ``Version`` keyword
``CMAKE_PKG_CONFIG_PROVIDES`` List Value of the ``Provides`` keyword
``CMAKE_PKG_CONFIG_REQUIRES`` List Value of the ``Requires`` keyword
``CMAKE_PKG_CONFIG_CONFLICTS`` List Value of the ``Conflicts`` keyword
``CMAKE_PKG_CONFIG_CFLAGS`` String Value of the ``CFlags`` / ``Cflags`` keyword
``CMAKE_PKG_CONFIG_INCLUDES`` List All ``-I`` prefixed flags from ``CMAKE_PKG_CONFIG_CFLAGS``
``CMAKE_PKG_CONFIG_COMPILE_OPTIONS`` List All flags not prefixed with ``-I`` from ``CMAKE_PKG_CONFIG_CFLAGS``
``CMAKE_PKG_CONFIG_LIBS`` String Value of the ``Libs`` keyword
``CMAKE_PKG_CONFIG_LIBDIRS`` List All ``-L`` prefixed flags from ``CMAKE_PKG_CONFIG_LIBS``
``CMAKE_PKG_CONFIG_LIBNAMES`` List All ``-l`` prefixed flags from ``CMAKE_PKG_CONFIG_LIBS``
``CMAKE_PKG_CONFIG_LINK_OPTIONS`` List All flags not prefixed with ``-L`` or ``-l`` from ``CMAKE_PKG_CONFIG_LIBS``
``CMAKE_PKG_CONFIG_*_PRIVATE`` \* ``CFLAGS`` / ``LIBS`` / ``REQUIRES`` and derived, but in their ``.private`` suffix forms
==================================== ====== ========================================================================================
``SYSTEM_INCLUDE_DIRS``
Overrides the "system" directories for the purpose of flag mangling include
directories in ``CMAKE_PKG_CONFIG_CFLAGS`` and derived variables.
When this option is not provided, the default directories are provided by the
first available of the following values:
#. ``CMAKE_PKG_CONFIG_SYS_INCLUDE_DIRS``
#. The ``PKG_CONFIG_SYSTEM_INCLUDE_PATH`` environment variable
#. The output of ``pkgconf --variable pc_system_includedirs pkg-config``
#. A platform-dependent default value
Additionally, when the ``ENV_MODE`` is ``PKGCONF`` the
``CMAKE_PKG_CONFIG_PKGCONF_INCLUDES`` variable will be concatenated to the
list if available. If it is not available, the following environment variables
will be queried and concatenated:
* ``CPATH``
* ``C_INCLUDE_PATH``
* ``CPLUS_INCLUDE_PATH``
* ``OBJC_INCLUDE_PATH``
* ``INCLUDE`` (Windows Only)
``SYSTEM_LIBRARY_DIRS``
Overrides the "system" directories for the purpose of flag mangling library
directories in ``CMAKE_PKG_CONFIG_LIBS`` and derived variables.
When this option is not provided, the default directories are provided by the
first available of the following values:
#. ``CMAKE_PKG_CONFIG_SYS_LIB_DIRS``
#. The ``PKG_CONFIG_SYSTEM_LIBRARY_PATH`` environment variable
#. The output of ``pkgconf --variable pc_system_libdirs pkg-config``
#. A platform-dependent default value
Additionally, when the ``ENV_MODE`` is ``PKGCONF`` the
``CMAKE_PKG_CONFIG_PKGCONF_LIB_DIRS`` variable will be concatenated to the
list if available. If it is not available, the ``LIBRARY_PATH`` environment
variable will be queried and concatenated.
``ALLOW_SYSTEM_INCLUDES``
Preserves "system" directories during flag mangling of include directories
in ``CMAKE_PKG_CONFIG_CFLAGS`` and derived variables.
When this option is not provided, the default value is determined by the first
available of the following values:
#. ``CMAKE_PKG_CONFIG_ALLOW_SYS_INCLUDES``
#. If the ``PKG_CONFIG_ALLOW_SYSTEM_CFLAGS`` environment variable is defined
the flags are preserved, otherwise they are filtered during flag mangling.
``ALLOW_SYSTEM_LIBS``
Preserves "system" directories during flag mangling of library directories
in ``CMAKE_PKG_CONFIG_LIBS`` and derived variables.
When this option is not provided, the default value is determined by the first
available of the following values:
#. ``CMAKE_PKG_CONFIG_ALLOW_SYS_LIBS``
#. If the ``PKG_CONFIG_ALLOW_SYSTEM_LIBS`` environment variable is defined
the flags are preserved, otherwise they are filtered during flag mangling.
.. signature::
cmake_pkg_config(POPULATE <package> [<version>] [...])
.. versionadded:: 4.1
Populate a package in the pkg-config target namespace
.. code-block:: cmake
cmake_pkg_config(POPULATE <package> [<version>]
[REQUIRED] [EXACT] [QUIET]
[PREFIX <prefix>]
[BIND_PC_REQUIRES <<name>=<target>>...]
[STRICTNESS <mode>]
[ENV_MODE <mode>]
[PC_LIBDIR <path>...]
[PC_PATH <path>...]
[DISABLE_UNINSTALLED <bool>]
[PC_SYSROOT_DIR <path>]
[TOP_BUILD_DIR <path>])
``POPULATE`` enables manual control of resolution of a given package's
``Requires`` list without importing onto a native CMake target. Once populated,
a package and its dependencies will be used for resolution of all future
``POPULATE`` and ``IMPORT`` commands.
A ``PKGCONFIG_<package>_FOUND`` variable will be set to indicate whether the
package was found.
.. signature::
cmake_pkg_config(IMPORT <package> [<version>] [...])
.. versionadded:: 4.1
Import a pkg-config target as a CMake :prop_tgt:`IMPORTED` target
.. code-block:: cmake
cmake_pkg_config(IMPORT <package> [<version>]
[REQUIRED] [EXACT] [QUIET]
[NAME <name>]
[PREFIX <prefix>]
[BIND_PC_REQUIRES <<name>=<target>>...]
[STRICTNESS <mode>]
[ENV_MODE <mode>]
[PC_LIBDIR <path>...]
[PC_PATH <path>...]
[DISABLE_UNINSTALLED <bool>]
[PC_SYSROOT_DIR <path>]
[TOP_BUILD_DIR <path>])
Creates a native CMake ``IMPORTED`` target that can be linked to via
:command:`target_link_libraries`. This new target is named
``PkgConfig::<package>`` by default.
A ``PKGCONFIG_<package>_FOUND`` variable will be set to indicate whether the
package was found.
``NAME``
Overrides the name of the created CMake target to ``PkgConfig::<name>``. This
*does not* affect the ``PKGCONFIG_<package>_FOUND`` variable.
@@ -0,0 +1,153 @@
cmake_policy
------------
Manage CMake Policy settings. See the :manual:`cmake-policies(7)`
manual for defined policies.
As CMake evolves it is sometimes necessary to change existing behavior
in order to fix bugs or improve implementations of existing features.
The CMake Policy mechanism is designed to help keep existing projects
building as new versions of CMake introduce changes in behavior. Each
new policy (behavioral change) is given an identifier of the form
``CMP<NNNN>`` where ``<NNNN>`` is an integer index. Documentation
associated with each policy describes the ``OLD`` and ``NEW`` behavior
and the reason the policy was introduced. Projects may set each policy
to select the desired behavior. When CMake needs to know which behavior
to use it checks for a setting specified by the project. If no
setting is available the ``OLD`` behavior is assumed and a warning is
produced requesting that the policy be set.
Setting Policies by CMake Version
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The ``cmake_policy`` command is used to set policies to ``OLD`` or ``NEW``
behavior. While setting policies individually is supported, we
encourage projects to set policies based on CMake versions:
.. signature:: cmake_policy(VERSION <min>[...<policy_max>])
:target: VERSION
.. versionadded:: 3.12
The optional ``<policy_max>`` version.
``<min>`` and the optional ``<policy_max>`` are each CMake versions of the
form ``major.minor[.patch[.tweak]]``, and the ``...`` is literal.
The ``<min>`` version must be at least ``2.4`` and at most the running
version of CMake. The ``<policy_max>`` version, if specified, must be at
least the ``<min>`` version but may exceed the running version of CMake.
If the running version of CMake is older than 3.12, the extra ``...``
dots will be seen as version component separators, resulting in the
``...<policy_max>`` part being ignored and preserving the pre-3.12 behavior
of basing policies on ``<min>``.
.. include:: include/POLICY_VERSION.rst
Note that the :command:`cmake_minimum_required(VERSION)`
command implicitly calls ``cmake_policy(VERSION)`` too.
.. include:: include/DEPRECATED_POLICY_VERSIONS.rst
Setting Policies Explicitly
^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. signature:: cmake_policy(SET CMP<NNNN> NEW|OLD)
:target: SET
Tell CMake to use the ``OLD`` or ``NEW`` behavior for a given policy.
Projects depending on the old behavior of a given policy may silence a
policy warning by setting the policy state to ``OLD``. Alternatively
one may fix the project to work with the new behavior and set the
policy state to ``NEW``.
.. include:: ../policy/include/DEPRECATED.rst
Checking Policy Settings
^^^^^^^^^^^^^^^^^^^^^^^^
.. signature:: cmake_policy(GET CMP<NNNN> <variable>)
:target: GET
Check whether a given policy is set to ``OLD`` or ``NEW`` behavior.
The output ``<variable>`` value will be ``OLD`` or ``NEW`` if the
policy is set, and empty otherwise.
CMake Policy Stack
^^^^^^^^^^^^^^^^^^
CMake keeps policy settings on a stack, so changes made by the
``cmake_policy`` command affect only the top of the stack. A new entry on
the policy stack is managed automatically for each subdirectory to
protect its parents and siblings. CMake also manages a new entry for
scripts loaded by :command:`include` and :command:`find_package` commands
except when invoked with the ``NO_POLICY_SCOPE`` option
(see also policy :policy:`CMP0011`).
The ``cmake_policy`` command provides an interface to manage custom
entries on the policy stack:
.. signature:: cmake_policy(PUSH)
:target: PUSH
Create a new entry on the policy stack.
.. signature:: cmake_policy(POP)
:target: POP
Remove the last policy stack entry created with ``cmake_policy(PUSH)``.
Each ``PUSH`` must have a matching ``POP`` to erase any changes.
This is useful to make temporary changes to policy settings.
Calls to the :command:`cmake_minimum_required(VERSION)`,
:command:`cmake_policy(VERSION)`, or :command:`cmake_policy(SET)` commands
influence only the current top of the policy stack.
.. versionadded:: 3.25
The :command:`block(SCOPE_FOR POLICIES)` command offers a more flexible
and more secure way to manage the policy stack. The pop action is done
automatically when leaving the block scope, so there is no need to
precede each :command:`return` with a call to :command:`cmake_policy(POP)`.
.. code-block:: cmake
# stack management with cmake_policy()
function(my_func)
cmake_policy(PUSH)
cmake_policy(SET ...)
if (<cond1>)
...
cmake_policy(POP)
return()
elseif(<cond2>)
...
cmake_policy(POP)
return()
endif()
...
cmake_policy(POP)
endfunction()
# stack management with block()/endblock()
function(my_func)
block(SCOPE_FOR POLICIES)
cmake_policy(SET ...)
if (<cond1>)
...
return()
elseif(<cond2>)
...
return()
endif()
...
endblock()
endfunction()
Commands created by the :command:`function` and :command:`macro`
commands record policy settings when they are created and
use the pre-record policies when they are invoked. If the function or
macro implementation sets policies, the changes automatically
propagate up through callers until they reach the closest nested
policy stack entry.
See Also
^^^^^^^^
* :command:`cmake_minimum_required`
@@ -0,0 +1,203 @@
configure_file
--------------
.. only:: html
.. contents::
Copy a file to another location and modify its contents.
.. code-block:: cmake
configure_file(<input> <output>
[NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS |
FILE_PERMISSIONS <permissions>...]
[COPYONLY] [ESCAPE_QUOTES] [@ONLY]
[NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF]])
Copies an ``<input>`` file to an ``<output>`` file while performing
`transformations`_ of the input file content.
If the input file is modified the build system will re-run CMake to
re-configure the file and generate the build system again.
The generated file is modified and its timestamp updated on subsequent
cmake runs only if its content is changed.
Options
^^^^^^^
The options are:
``<input>``
Path to the input file. A relative path is treated with respect to
the value of :variable:`CMAKE_CURRENT_SOURCE_DIR`. The input path
must be a file, not a directory.
``<output>``
Path to the output file or directory. A relative path is treated
with respect to the value of :variable:`CMAKE_CURRENT_BINARY_DIR`.
If the path names an existing directory the output file is placed
in that directory with the same file name as the input file.
If the path contains non-existent directories, they are created.
``NO_SOURCE_PERMISSIONS``
.. versionadded:: 3.19
Do not transfer the permissions of the input file to the output file.
The copied file permissions default to the standard 644 value
(-rw-r--r--).
``USE_SOURCE_PERMISSIONS``
.. versionadded:: 3.20
Transfer the permissions of the input file to the output file.
This is already the default behavior if none of the three permissions-related
keywords are given (``NO_SOURCE_PERMISSIONS``, ``USE_SOURCE_PERMISSIONS``
or ``FILE_PERMISSIONS``). The ``USE_SOURCE_PERMISSIONS`` keyword mostly
serves as a way of making the intended behavior clearer at the call site.
``FILE_PERMISSIONS <permissions>...``
.. versionadded:: 3.20
Ignore the input file's permissions and use the specified ``<permissions>``
for the output file instead.
``COPYONLY``
Copy the file without replacing any variable references or other
content. This option may not be used with ``NEWLINE_STYLE``.
``ESCAPE_QUOTES``
Escape any substituted quotes with backslashes (C-style).
``@ONLY``
Restrict variable replacement to references of the form ``@VAR@``.
This is useful for configuring scripts that use ``${VAR}`` syntax.
``NEWLINE_STYLE <style>``
Specify the newline style for the output file. Specify
``UNIX`` or ``LF`` for ``\n`` newlines, or specify
``DOS``, ``WIN32``, or ``CRLF`` for ``\r\n`` newlines.
This option may not be used with ``COPYONLY``.
Transformations
^^^^^^^^^^^^^^^
:ref:`Variables <CMake Language Variables>` referenced in the input
file content as ``@VAR@``, ``${VAR}``, ``$CACHE{VAR}``, and
:ref:`environment variables <CMake Language Environment Variables>`
referenced as ``$ENV{VAR}``, will each be replaced with the current value
of the variable, or the empty string if the variable is not defined.
Furthermore, input lines of the form
.. code-block:: c
#cmakedefine VAR ...
will be replaced with either
.. code-block:: c
#define VAR ...
or
.. code-block:: c
/* #undef VAR */
depending on whether ``VAR`` is set in CMake to any value not considered
a false constant by the :command:`if` command. The "..." content on the
line after the variable name, if any, is processed as above.
Unlike lines of the form ``#cmakedefine VAR ...``, in lines of the form
``#cmakedefine01 VAR``, ``VAR`` itself will expand to ``VAR 0`` or ``VAR 1``
rather than being assigned the value ``...``. Therefore, input lines of the form
.. code-block:: c
#cmakedefine01 VAR
will be replaced with either
.. code-block:: c
#define VAR 0
or
.. code-block:: c
#define VAR 1
Input lines of the form ``#cmakedefine01 VAR ...`` will expand
as ``#cmakedefine01 VAR ... 0`` or ``#cmakedefine01 VAR ... 1``,
which may lead to undefined behavior.
.. versionadded:: 3.10
The result lines (with the exception of the ``#undef`` comments) can be
indented using spaces and/or tabs between the ``#`` character
and the ``cmakedefine`` or ``cmakedefine01`` words. This whitespace
indentation will be preserved in the output lines:
.. code-block:: c
# cmakedefine VAR
# cmakedefine01 VAR
will be replaced, if ``VAR`` is defined, with
.. code-block:: c
# define VAR
# define VAR 1
Example
^^^^^^^
Consider a source tree containing a ``foo.h.in`` file:
.. code-block:: c
#cmakedefine FOO_ENABLE
#cmakedefine FOO_STRING "@FOO_STRING@"
An adjacent ``CMakeLists.txt`` may use ``configure_file`` to
configure the header:
.. code-block:: cmake
option(FOO_ENABLE "Enable Foo" ON)
if(FOO_ENABLE)
set(FOO_STRING "foo")
endif()
configure_file(foo.h.in foo.h @ONLY)
This creates a ``foo.h`` in the build directory corresponding to
this source directory. If the ``FOO_ENABLE`` option is on, the
configured file will contain:
.. code-block:: c
#define FOO_ENABLE
#define FOO_STRING "foo"
Otherwise it will contain:
.. code-block:: c
/* #undef FOO_ENABLE */
/* #undef FOO_STRING */
One may then use the :command:`target_include_directories` command to
specify the output directory as an include directory:
.. code-block:: cmake
target_include_directories(<target> [SYSTEM] {INTERFACE|PUBLIC|PRIVATE} "${CMAKE_CURRENT_BINARY_DIR}")
so that sources may include the header as ``#include <foo.h>``.
See Also
^^^^^^^^
* :command:`file(GENERATE)`
@@ -0,0 +1,16 @@
continue
--------
.. versionadded:: 3.2
Continue to the top of enclosing foreach or while loop.
.. code-block:: cmake
continue()
The ``continue()`` command allows a cmake script to abort the rest of the
current iteration of a :command:`foreach` or :command:`while` loop, and start
at the top of the next iteration.
See also the :command:`break` command.
@@ -0,0 +1,103 @@
create_test_sourcelist
----------------------
Create a test driver program that links together many small tests into a
single executable. This is useful when building static executables with
large libraries to shrink the total required size.
.. signature::
create_test_sourcelist(<sourceListName> <driverName> <test>... <options>...)
:target: original
Generate a test driver source file from a list of individual test sources
and provide a combined list of sources that can be built as an executable.
The options are:
``<sourceListName>``
The name of a variable in which to store the list of source files needed
to build the test driver. The list will contain the ``<test>...`` sources
and the generated ``<driverName>`` source.
.. versionchanged:: 3.29
The test driver source is listed by absolute path in the build tree.
Previously it was listed only as ``<driverName>``.
``<driverName>``
Name of the test driver source file to be generated into the build tree.
The source file will contain a ``main()`` program entry point that
dispatches to whatever test is named on the command line.
``<test>...``
Test source files to be added to the driver binary. Each test source
file must have a function in it that is the same name as the file with the
extension removed. For example, a ``foo.cxx`` test source might contain:
.. code-block:: c++
int foo(int argc, char** argv)
``EXTRA_INCLUDE <header>``
Specify a header file to ``#include`` in the generated test driver source.
``FUNCTION <function>``
Specify a function to be called with pointers to ``argc`` and ``argv``.
The function may be provided in the ``EXTRA_INCLUDE`` header:
.. code-block:: c++
void function(int* pargc, char*** pargv)
This can be used to add extra command line processing to each test.
Additionally, some CMake variables affect test driver generation:
.. variable:: CMAKE_TESTDRIVER_BEFORE_TESTMAIN
Code to be placed directly before calling each test's function.
.. variable:: CMAKE_TESTDRIVER_AFTER_TESTMAIN
Code to be placed directly after the call to each test's function.
The generated test driver supports the following command-line arguments:
``<name>``
Run the test with the exact name ``<name>`` (case-insensitive).
``-R <substr>``
Run the first test whose name contains ``<substr>`` (case-insensitive).
``-A [<skip_test>...]``
.. versionadded:: 3.21
Run all tests and print results in `TAP <https://testanything.org/>`_
format.
Any additional arguments after ``-A`` are interpreted as exact test names
to skip.
``-N``
.. versionadded:: 4.4
List all available test names (one per line) and exit.
Example
^^^^^^^
.. code-block:: cmake
create_test_sourcelist(SRCS main.c test1.c test2.c)
add_executable(MyTests ${SRCS})
discover_tests(COMMAND MyTests
DISCOVERY_ARGS -N
DISCOVERY_MATCH "^(.+)$"
TEST_NAME "${PROJECT_NAME}.\\1"
TEST_ARGS "\\1"
)
See Also
^^^^^^^^
* :command:`discover_tests`
@@ -0,0 +1,122 @@
ctest_build
-----------
Perform the :ref:`CTest Build Step` as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_build([BUILD <build-dir>] [APPEND]
[CONFIGURATION <config>]
[PARALLEL_LEVEL <parallel>]
[FLAGS <flags>]
[PROJECT_NAME <project-name>]
[TARGET <target-name>]
[NUMBER_ERRORS <num-err-var>]
[NUMBER_WARNINGS <num-warn-var>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[PRESET <preset>]
[PRESETS_FILE <file>]
)
Build the project and store results in ``Build.xml``
for submission with the :command:`ctest_submit` command.
The :variable:`CTEST_BUILD_COMMAND` variable may be set to explicitly
specify the build command line when no preset is selected. Otherwise
the build command line is computed automatically based on the options given.
The options are:
``BUILD <build-dir>``
Specify the top-level build directory. If not given, the
:variable:`CTEST_BINARY_DIRECTORY` variable is used.
``APPEND``
Mark ``Build.xml`` for append to results previously submitted to a
dashboard server since the last :command:`ctest_start` call.
Append semantics are defined by the dashboard server in use.
This does *not* cause results to be appended to a ``.xml`` file
produced by a previous call to this command.
``CONFIGURATION <config>``
Specify the build configuration (e.g. ``Debug``). If not
specified the ``CTEST_BUILD_CONFIGURATION`` variable will be checked.
Otherwise the :option:`-C \<cfg\> <ctest -C>` option given to the
:manual:`ctest(1)` command will be used, if any.
``PARALLEL_LEVEL <parallel>``
.. versionadded:: 3.21
Specify the parallel level of the underlying build system. If not
specified, the :envvar:`CMAKE_BUILD_PARALLEL_LEVEL` environment
variable will be checked.
``FLAGS <flags>``
Pass additional arguments to the underlying build command.
If not specified the ``CTEST_BUILD_FLAGS`` variable will be checked.
This can, e.g., be used to trigger a parallel build using the
``-j`` option of ``make``. See the :module:`ProcessorCount` module
for an example.
``PROJECT_NAME <project-name>``
Ignored since CMake 3.0.
.. versionchanged:: 3.14
This value is no longer required.
``TARGET <target-name>``
Specify the name of a target to build. If not specified the
``CTEST_BUILD_TARGET`` variable will be checked. Otherwise the
default target will be built. This is the "all" target
(called ``ALL_BUILD`` in :ref:`Visual Studio Generators`).
``NUMBER_ERRORS <num-err-var>``
Store the number of build errors detected in the given variable.
``NUMBER_WARNINGS <num-warn-var>``
Store the number of build warnings detected in the given variable.
``PRESET <preset>``
.. versionadded:: 4.4
Specify a :manual:`preset <cmake-presets(7)>` to use when building the
project. Any value set in the CTest script will take priority over a
corresponding setting from the preset. For example, the ``TARGET``
argument will override the :preset:`buildPresets.targets` setting from
the chosen preset.
When a preset is specified, the :variable:`CTEST_BUILD_COMMAND`
variable is ignored so that the preset is always honored.
See also the :variable:`CTEST_BUILD_PRESET` and
:variable:`CTEST_PRESET` variables.
``PRESETS_FILE <file>``
.. versionadded:: 4.4
Specify a :manual:`presets <cmake-presets(7)>` file to use instead of the
default ``CMakePresets.json`` in the source directory.
A relative path is interpreted relative to the source directory.
Has no effect unless a preset is selected via the ``PRESET`` argument
or the :variable:`CTEST_BUILD_PRESET` or :variable:`CTEST_PRESET`
variables.
See also the :variable:`CTEST_PRESETS_FILE` variable.
``RETURN_VALUE <result-var>``
Store the return value of the native build tool in the given variable.
``CAPTURE_CMAKE_ERROR <result-var>``
.. versionadded:: 3.7
Store in the ``<result-var>`` variable -1 if there are any errors running
the command and prevent ctest from returning non-zero if an error occurs.
``QUIET``
.. versionadded:: 3.3
Suppress any CTest-specific non-error output that would have been
printed to the console otherwise. The summary of warnings / errors,
as well as the output from the native build tool is unaffected by
this option.
@@ -0,0 +1,83 @@
ctest_configure
---------------
Perform the :ref:`CTest Configure Step` as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_configure([BUILD <build-dir>] [SOURCE <source-dir>] [APPEND]
[OPTIONS <options>] [RETURN_VALUE <result-var>] [QUIET]
[CAPTURE_CMAKE_ERROR <result-var>]
[PRESET <preset>]
[PRESETS_FILE <file>]
)
Configure the project build tree and record results in ``Configure.xml``
for submission with the :command:`ctest_submit` command.
The options are:
``BUILD <build-dir>``
Specify the top-level build directory. If not given, the
:variable:`CTEST_BINARY_DIRECTORY` variable is used.
``SOURCE <source-dir>``
Specify the source directory. If not given, the
:variable:`CTEST_SOURCE_DIRECTORY` variable is used.
``APPEND``
Mark ``Configure.xml`` for append to results previously submitted to a
dashboard server since the last :command:`ctest_start` call.
Append semantics are defined by the dashboard server in use.
This does *not* cause results to be appended to a ``.xml`` file
produced by a previous call to this command.
``OPTIONS <options>``
Specify a :ref:`semicolon-separated list <CMake Language Lists>` of
command-line arguments to pass to the configuration tool.
This option is ignored when :variable:`CTEST_CONFIGURE_COMMAND` is used.
``PRESET <preset>``
.. versionadded:: 4.4
Specify a :manual:`preset <cmake-presets(7)>` to use when configuring the
project. Any value set in the CTest script will take priority over a
corresponding setting from the preset. For example, the
:variable:`CTEST_BINARY_DIRECTORY` variable will override the
:preset:`configurePresets.binaryDir` setting from the chosen preset.
When a preset is specified, the :variable:`CTEST_CONFIGURE_COMMAND`
variable is ignored so that the preset is always honored.
See also the :variable:`CTEST_CONFIGURE_PRESET` and
:variable:`CTEST_PRESET` variables.
``PRESETS_FILE <file>``
.. versionadded:: 4.4
Specify a :manual:`presets <cmake-presets(7)>` file to use instead of the
default ``CMakePresets.json`` in the source directory.
A relative path is interpreted relative to the source directory.
Has no effect unless a preset is selected via the ``PRESET`` argument
or the :variable:`CTEST_CONFIGURE_PRESET` or :variable:`CTEST_PRESET`
variables.
See also the :variable:`CTEST_PRESETS_FILE` variable.
``RETURN_VALUE <result-var>``
Store in the ``<result-var>`` variable the return value of the native
configuration tool.
``CAPTURE_CMAKE_ERROR <result-var>``
.. versionadded:: 3.7
Store in the ``<result-var>`` variable ``-1`` if there are any errors running
the command and prevent :manual:`ctest(1)` from returning non-zero if an
error occurs.
``QUIET``
.. versionadded:: 3.3
Suppress any CTest-specific non-error messages that would have
otherwise been printed to the console. Output from the underlying
configure command is not affected.
@@ -0,0 +1,51 @@
ctest_coverage
--------------
Perform the :ref:`CTest Coverage Step` as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_coverage([BUILD <build-dir>] [APPEND]
[LABELS <label>...]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[QUIET]
)
Collect coverage tool results and stores them in ``Coverage.xml``
for submission with the :command:`ctest_submit` command.
The options are:
``BUILD <build-dir>``
Specify the top-level build directory. If not given, the
:variable:`CTEST_BINARY_DIRECTORY` variable is used.
``APPEND``
Mark ``Coverage.xml`` for append to results previously submitted to a
dashboard server since the last :command:`ctest_start` call.
Append semantics are defined by the dashboard server in use.
This does *not* cause results to be appended to a ``.xml`` file
produced by a previous call to this command.
``LABELS``
Filter the coverage report to include only source files labeled
with at least one of the labels specified.
``RETURN_VALUE <result-var>``
Store in the ``<result-var>`` variable ``0`` if coverage tools
ran without error and non-zero otherwise.
``CAPTURE_CMAKE_ERROR <result-var>``
.. versionadded:: 3.7
Store in the ``<result-var>`` variable ``-1`` if there are any errors running
the command and prevent :manual:`ctest(1)` from returning non-zero if an
error occurs.
``QUIET``
.. versionadded:: 3.3
Suppress any CTest-specific non-error output that would have been
printed to the console otherwise. The summary indicating how many
lines of code were covered is unaffected by this option.
@@ -0,0 +1,12 @@
ctest_empty_binary_directory
----------------------------
Empties the binary directory.
.. code-block:: cmake
ctest_empty_binary_directory(<directory>)
Removes a binary directory. This command will perform some checks
prior to deleting the directory in an attempt to avoid malicious or
accidental directory deletion.
@@ -0,0 +1,47 @@
ctest_memcheck
--------------
Perform the :ref:`CTest MemCheck Step` as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_memcheck([BUILD <build-dir>] [APPEND]
[START <start-number>]
[END <end-number>]
[STRIDE <stride-number>]
[EXCLUDE <exclude-regex>]
[INCLUDE <include-regex>]
[EXCLUDE_LABEL <label-exclude-regex>]
[INCLUDE_LABEL <label-include-regex>]
[EXCLUDE_FIXTURE <regex>]
[EXCLUDE_FIXTURE_SETUP <regex>]
[EXCLUDE_FIXTURE_CLEANUP <regex>]
[PARALLEL_LEVEL <level>]
[RESOURCE_SPEC_FILE <file>]
[TEST_LOAD <threshold>]
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_ON_FAILURE]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[REPEAT <mode>:<n>]
[OUTPUT_JUNIT <file>]
[PRESET <preset>]
[PRESETS_FILE <path>]
[DEFECT_COUNT <defect-count-var>]
[QUIET]
)
Run tests with a dynamic analysis tool and store results in
``MemCheck.xml`` for submission with the :command:`ctest_submit`
command.
Most options are the same as those for the :command:`ctest_test` command.
The options unique to this command are:
``DEFECT_COUNT <defect-count-var>``
.. versionadded:: 3.8
Store in the ``<defect-count-var>`` the number of defects found.
@@ -0,0 +1,14 @@
ctest_read_custom_files
-----------------------
Read CTestCustom files.
.. code-block:: cmake
ctest_read_custom_files(<directory>...)
Read all the ``CTestCustom.ctest`` or ``CTestCustom.cmake`` files from the
given directory.
By default, invoking :manual:`ctest(1)` without a script will read custom
files from the binary directory.
@@ -0,0 +1,21 @@
ctest_run_script
----------------
Run a :option:`ctest -S` script.
.. code-block:: cmake
ctest_run_script([NEW_PROCESS]
<script-file>...
[RETURN_VALUE <result-var>]
)
Runs a script or scripts much like if it was run from :option:`ctest -S`.
The options are:
``NEW_PROCESS``
Run each script in a separate process.
``RETURN_VALUE <result-var>``
Store in the ``<result-var>`` variable ``0`` for success and
non-zero on failure.
@@ -0,0 +1,15 @@
ctest_sleep
-----------
Sleep for some amount of time.
.. signature::
ctest_sleep(<seconds>)
Sleep for ``<seconds>`` seconds.
.. signature::
ctest_sleep(<time1> <duration> <time2>)
Sleep for ``<time1> + <duration> - <time2>`` seconds, if this sum is greater
than zero.
@@ -0,0 +1,88 @@
ctest_start
-----------
Perform the :ref:`CTest Start Step` as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_start(<model> [<source> [<binary>]] [GROUP <group>] [QUIET])
ctest_start([<model> [<source> [<binary>]]] [GROUP <group>] APPEND [QUIET])
Starts the testing for a given model. The command should be called
after the binary directory is initialized.
The parameters are as follows:
``<model>``
Set the dashboard model. Must be one of ``Experimental``, ``Continuous``, or
``Nightly``. This parameter is required unless ``APPEND`` is specified.
``<source>``
Set the source directory. If not specified, the value of
:variable:`CTEST_SOURCE_DIRECTORY` is used instead.
``<binary>``
Set the binary directory. If not specified, the value of
:variable:`CTEST_BINARY_DIRECTORY` is used instead.
``GROUP <group>``
If ``GROUP`` is used, the submissions will go to the specified group on the
CDash server. If no ``GROUP`` is specified, the name of the model is used by
default.
.. versionchanged:: 3.16
This replaces the deprecated option ``TRACK``. Despite the name
change its behavior is unchanged.
``APPEND``
If ``APPEND`` is used, the existing ``TAG`` is used rather than creating a new
one based on the current time stamp. If you use ``APPEND``, you can omit the
``<model>`` and ``GROUP <group>`` parameters, because they will be read from
the generated ``TAG`` file. For example:
.. code-block:: cmake
ctest_start(Experimental GROUP GroupExperimental)
Later, in another :option:`ctest -S` script:
.. code-block:: cmake
ctest_start(APPEND)
When the second script runs ``ctest_start(APPEND)``, it will read the
``Experimental`` model and ``GroupExperimental`` group from the ``TAG`` file
generated by the first ``ctest_start()`` command. Please note that if you
call ``ctest_start(APPEND)`` and specify a different model or group than
in the first ``ctest_start()`` command, a warning will be issued, and the
new model and group will be used.
``QUIET``
.. versionadded:: 3.3
If ``QUIET`` is used, CTest will suppress any non-error messages that it
otherwise would have printed to the console.
The parameters for ``ctest_start()`` can be issued in any order, with the
exception that ``<model>``, ``<source>``, and ``<binary>`` have to appear
in that order with respect to each other. The following are all valid and
equivalent:
.. code-block:: cmake
ctest_start(Experimental path/to/source path/to/binary GROUP SomeGroup QUIET APPEND)
ctest_start(GROUP SomeGroup Experimental QUIET path/to/source APPEND path/to/binary)
ctest_start(APPEND QUIET Experimental path/to/source GROUP SomeGroup path/to/binary)
However, for the sake of readability, it is recommended that you order your
parameters in the order listed at the top of this page.
If the :variable:`CTEST_CHECKOUT_COMMAND` variable is set, its content is
treated as
command-line. The command is invoked with the current working directory set
to the parent of the source directory, even if the source directory already
exists. This can be used to create the source tree from a version control
repository.
@@ -0,0 +1,135 @@
ctest_submit
------------
Perform the :ref:`CTest Submit Step` as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_submit([PARTS <part>...] [FILES <file>...]
[SUBMIT_URL <url>]
[BUILD_ID <result-var>]
[HTTPHEADER <header>]
[RETRY_COUNT <count>]
[RETRY_DELAY <delay>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[QUIET]
)
Submit results to a dashboard server.
By default all available parts are submitted.
The options are:
``PARTS <part>...``
Specify a subset of parts to submit. Takes precedence over the
:variable:`CTEST_SUBMIT_PARTS` variable if both are set.
Valid part names are:
* ``Start`` - nothing.
* ``Update`` - :command:`ctest_update` results, in ``Update.xml``.
* ``Configure`` - :command:`ctest_configure` results, in ``Configure.xml``.
* ``Build`` - :command:`ctest_build` results, in ``Build.xml``.
* ``Test`` - :command:`ctest_test` results, in ``Test.xml``.
* ``Coverage`` - :command:`ctest_coverage` results, in ``Coverage.xml``.
* ``MemCheck`` - :command:`ctest_memcheck` results, in
``DynamicAnalysis.xml`` and ``DynamicAnalysis-Test.xml``.
* ``Notes`` - Files listed by :variable:`CTEST_NOTES_FILES`, in ``Notes.xml``.
* ``ExtraFiles`` - Files listed by :variable:`CTEST_EXTRA_SUBMIT_FILES`.
* ``Upload`` - Files prepared for upload by :command:`ctest_upload`, in
``Upload.xml``.
* ``Submit`` - nothing.
* ``Done`` - Build is complete, in ``Done.xml``.
``FILES <file>...``
Specify an explicit list of specific files to be submitted.
Each individual file must exist at the time of the call.
``SUBMIT_URL <url>``
.. versionadded:: 3.14
The ``http`` or ``https`` URL of the dashboard server to send the submission
to. If not given, the :variable:`CTEST_SUBMIT_URL` variable is used.
``BUILD_ID <result-var>``
.. versionadded:: 3.15
Store in the ``<result-var>`` variable the ID assigned to this build by
CDash.
``HTTPHEADER <HTTP-header>``
.. versionadded:: 3.9
Specify HTTP header to be included in the request to CDash during submission.
For example, CDash can be configured to only accept submissions from
authenticated clients. In this case, you should provide a bearer token in your
header:
.. code-block:: cmake
ctest_submit(HTTPHEADER "Authorization: Bearer <auth-token>")
This suboption can be repeated several times for multiple headers.
``RETRY_COUNT <count>``
Specify how many times to retry a timed-out submission.
``RETRY_DELAY <delay>``
Specify how long (in seconds) to wait after a timed-out submission
before attempting to re-submit.
``RETURN_VALUE <result-var>``
Store in the ``<result-var>`` variable ``0`` for success and
non-zero on failure.
``CAPTURE_CMAKE_ERROR <result-var>``
.. versionadded:: 3.13
Store in the ``<result-var>`` variable ``-1`` if there are any errors running
the command and prevent :manual:`ctest(1)` from returning non-zero if an
error occurs.
``QUIET``
.. versionadded:: 3.3
Suppress all non-error messages that would have otherwise been
printed to the console.
Submit to CDash Upload API
^^^^^^^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.2
.. code-block:: cmake
ctest_submit(CDASH_UPLOAD <file> [CDASH_UPLOAD_TYPE <type>]
[SUBMIT_URL <url>]
[BUILD_ID <result-var>]
[HTTPHEADER <header>]
[RETRY_COUNT <count>]
[RETRY_DELAY <delay>]
[RETURN_VALUE <result-var>]
[QUIET])
This second signature is used to upload files to CDash via the CDash
file upload API. The API first sends a request to upload to CDash along
with a content hash of the file. If CDash does not already have the file,
then it is uploaded. Along with the file, a CDash type string is specified
to tell CDash which handler to use to process the data.
This signature interprets options in the same way as the first one.
.. versionadded:: 3.8
Added the ``RETRY_COUNT``, ``RETRY_DELAY``, ``QUIET`` options.
.. versionadded:: 3.9
Added the ``HTTPHEADER`` option.
.. versionadded:: 3.13
Added the ``RETURN_VALUE`` option.
.. versionadded:: 3.14
Added the ``SUBMIT_URL`` option.
.. versionadded:: 3.15
Added the ``BUILD_ID`` option.
@@ -0,0 +1,379 @@
ctest_test
----------
Perform the :ref:`CTest Test Step` as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_test([BUILD <build-dir>] [APPEND]
[START <start-number>]
[END <end-number>]
[STRIDE <stride-number>]
[EXCLUDE <exclude-regex>]
[INCLUDE <include-regex>]
[EXCLUDE_LABEL <label-exclude-regex>]
[INCLUDE_LABEL <label-include-regex>]
[EXCLUDE_FROM_FILE <filename>]
[INCLUDE_FROM_FILE <filename>]
[EXCLUDE_FIXTURE <regex>]
[EXCLUDE_FIXTURE_SETUP <regex>]
[EXCLUDE_FIXTURE_CLEANUP <regex>]
[PARALLEL_LEVEL [<level>]]
[RESOURCE_SPEC_FILE <file>]
[TEST_LOAD <threshold>]
[SCHEDULE_RANDOM <ON|OFF>]
[STOP_ON_FAILURE]
[STOP_TIME <time-of-day>]
[RETURN_VALUE <result-var>]
[CAPTURE_CMAKE_ERROR <result-var>]
[REPEAT <mode>:<n>]
[OUTPUT_JUNIT <file>]
[PRESET <preset>]
[PRESETS_FILE <file>]
[QUIET]
)
..
NOTE If updating the argument list here, please also update the argument
list documentation for :command:`ctest_memcheck` as well.
Run tests in the project build tree and store results in
``Test.xml`` for submission with the :command:`ctest_submit` command.
The options are:
``BUILD <build-dir>``
Specify the top-level build directory. If not given, the
:variable:`CTEST_BINARY_DIRECTORY` variable is used.
``APPEND``
Mark ``Test.xml`` for append to results previously submitted to a
dashboard server since the last :command:`ctest_start` call.
Append semantics are defined by the dashboard server in use.
This does *not* cause results to be appended to a ``.xml`` file
produced by a previous call to this command.
``START <start-number>``
Specify the beginning of a range of test numbers.
``END <end-number>``
Specify the end of a range of test numbers.
``STRIDE <stride-number>``
Specify the stride by which to step across a range of test numbers.
``EXCLUDE <exclude-regex>``
Specify a regular expression matching test names to exclude.
``INCLUDE <include-regex>``
Specify a regular expression matching test names to include.
Tests not matching this expression are excluded.
``EXCLUDE_LABEL <label-exclude-regex>``
Specify a regular expression matching test labels to exclude.
``INCLUDE_LABEL <label-include-regex>``
Specify a regular expression matching test labels to include.
Tests not matching this expression are excluded.
``EXCLUDE_FROM_FILE <filename>``
.. versionadded:: 3.29
Do NOT run tests listed with their exact name in the given file.
``INCLUDE_FROM_FILE <filename>``
.. versionadded:: 3.29
Only run the tests listed with their exact name in the given file.
``EXCLUDE_FIXTURE <regex>``
.. versionadded:: 3.7
If a test in the set of tests to be executed requires a particular fixture,
that fixture's setup and cleanup tests would normally be added to the test
set automatically. This option prevents adding setup or cleanup tests for
fixtures matching the ``<regex>``. Note that all other fixture behavior is
retained, including test dependencies and skipping tests that have fixture
setup tests that fail.
``EXCLUDE_FIXTURE_SETUP <regex>``
.. versionadded:: 3.7
Same as ``EXCLUDE_FIXTURE`` except only matching setup tests are excluded.
``EXCLUDE_FIXTURE_CLEANUP <regex>``
.. versionadded:: 3.7
Same as ``EXCLUDE_FIXTURE`` except only matching cleanup tests are excluded.
``PARALLEL_LEVEL [<level>]``
Run tests in parallel, limited to a given level of parallelism.
.. versionadded:: 3.29
The ``<level>`` may be omitted, or ``0``, to let :manual:`ctest(1)` use a
default level of parallelism, or unbounded parallelism, respectively, as
documented by the :option:`ctest --parallel` option.
If given, this argument takes precedence over a test preset's
:preset:`testPresets.execution.jobs` field. Both this argument and that
field take precedence over the :envvar:`CTEST_PARALLEL_LEVEL` environment
variable, and over an explicit :option:`ctest --parallel` given on the
command line. See :envvar:`CTEST_PARALLEL_LEVEL` for the full precedence
order.
``RESOURCE_SPEC_FILE <file>``
.. versionadded:: 3.16
Specify a
:ref:`resource specification file <ctest-resource-specification-file>`. See
:ref:`ctest-resource-allocation` for more information.
``TEST_LOAD <threshold>``
.. versionadded:: 3.4
While running tests in parallel, try not to start tests when they
may cause the CPU load to pass above a given threshold. If not
specified the :variable:`CTEST_TEST_LOAD` variable will be checked,
and then the :option:`--test-load <ctest --test-load>` command-line
argument to :manual:`ctest(1)`. See also the ``TestLoad`` setting
in the :ref:`CTest Test Step`.
``REPEAT <mode>:<n>``
.. versionadded:: 3.17
Run tests repeatedly based on the given ``<mode>`` up to ``<n>`` times.
The modes are:
``UNTIL_FAIL``
Require each test to run ``<n>`` times without failing in order to pass.
This is useful in finding sporadic failures in test cases.
``UNTIL_PASS``
Allow each test to run up to ``<n>`` times in order to pass.
Repeats tests if they fail for any reason.
This is useful in tolerating sporadic failures in test cases.
``AFTER_TIMEOUT``
Allow each test to run up to ``<n>`` times in order to pass.
Repeats tests only if they timeout.
This is useful in tolerating sporadic timeouts in test cases
on busy machines.
``SCHEDULE_RANDOM <ON|OFF>``
Launch tests in a random order. This may be useful for detecting
implicit test dependencies.
``STOP_ON_FAILURE``
.. versionadded:: 3.18
Stop the execution of the tests once one has failed.
``STOP_TIME <time-of-day>``
Specify a time of day at which the tests should all stop running.
``RETURN_VALUE <result-var>``
Store in the ``<result-var>`` variable ``0`` if all tests passed.
Store non-zero if anything went wrong.
``CAPTURE_CMAKE_ERROR <result-var>``
.. versionadded:: 3.7
Store in the ``<result-var>`` variable ``-1`` if there are any errors running
the command and prevent :manual:`ctest(1)` from returning non-zero if an
error occurs.
``OUTPUT_JUNIT <file>``
.. versionadded:: 3.21
Write test results to ``<file>`` in JUnit XML format. If ``<file>`` is a
relative path, it will be placed in the build directory. If ``<file>``
already exists, it will be overwritten. Note that the resulting JUnit XML
file is **not** uploaded to CDash because it would be redundant with
CTest's ``Test.xml`` file.
``COVERAGE_TOOL <tool>``
.. versionadded:: 4.4
Specify the ``<tool>`` used for collecting coverage during the running
of the tests. See the CTest :ref:`CoverageTool <ctest-CoverageTool>`
setting for details.
``PRESET <preset>``
.. versionadded:: 4.4
Specify a :manual:`preset <cmake-presets(7)>` to use when running tests.
Any value set in the CTest script will take priority over a corresponding
setting from the preset. For example, the ``INCLUDE`` argument will override
the :preset:`filter.include.name <testPresets.filter.include.name>` setting
from the chosen preset.
This option also applies to the :command:`ctest_memcheck` command.
See also the :variable:`CTEST_TEST_PRESET` and
:variable:`CTEST_PRESET` variables.
In general, only preset fields which have equivalent options to
``ctest_test`` are supported. An exception is the
:preset:`testPresets.environment`, which can hold a value for the
:envvar:`CTEST_NO_TESTS_ACTION` environment variable and will be respected,
despite ``ctest_test`` not having an equivalent option to the
:preset:`testPresets.execution.noTestsAction` presets field.
``PRESETS_FILE <file>``
.. versionadded:: 4.4
Specify a :manual:`presets <cmake-presets(7)>` file to use instead of the
default ``CMakePresets.json`` in the source directory.
A relative path is interpreted relative to the source directory.
Has no effect unless a preset is selected via the ``PRESET`` argument
or the :variable:`CTEST_TEST_PRESET` or :variable:`CTEST_PRESET`
variables.
This option also applies to the :command:`ctest_memcheck` command.
See also the :variable:`CTEST_PRESETS_FILE` variable.
``QUIET``
.. versionadded:: 3.3
Suppress any CTest-specific non-error messages that would have otherwise
been printed to the console. Output from the underlying test command is not
affected. Summary info detailing the percentage of passing tests is also
unaffected by the ``QUIET`` option.
See also the :variable:`CTEST_CUSTOM_MAXIMUM_PASSED_TEST_OUTPUT_SIZE`,
:variable:`CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE` and
:variable:`CTEST_CUSTOM_TEST_OUTPUT_TRUNCATION` variables, along with their
corresponding :manual:`ctest(1)` command line options
:ctest-option:`--test-output-size-passed`,
:ctest-option:`--test-output-size-failed`, and
:ctest-option:`--test-output-truncation`.
.. _`Additional Test Measurements`:
Additional Test Measurements
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
CTest can parse the output of your tests for extra measurements to report
to CDash.
When run as a :ref:`Dashboard Client`, CTest will include these custom
measurements in the ``Test.xml`` file that gets uploaded to CDash.
Check the `CDash test measurement documentation
<https://github.com/Kitware/CDash/blob/master/docs/test_measurements.md>`_
for more information on the types of test measurements that CDash recognizes.
.. versionadded:: 3.22
CTest can parse custom measurements from tags named
``<CTestMeasurement>`` or ``<CTestMeasurementFile>``. The older names
``<DartMeasurement>`` and ``<DartMeasurementFile>`` are still supported.
The following example demonstrates how to output a variety of custom test
measurements.
.. code-block:: c++
std::cout <<
"<CTestMeasurement type=\"numeric/double\" name=\"score\">28.3</CTestMeasurement>"
<< std::endl;
std::cout <<
"<CTestMeasurement type=\"text/string\" name=\"color\">red</CTestMeasurement>"
<< std::endl;
std::cout <<
"<CTestMeasurement type=\"text/link\" name=\"CMake URL\">https://cmake.org</CTestMeasurement>"
<< std::endl;
std::cout <<
"<CTestMeasurement type=\"text/preformatted\" name=\"Console Output\">" <<
"line 1.\n" <<
" \033[31;1m line 2. Bold red, and indented!\033[0;0ml\n" <<
"line 3. Not bold or indented...\n" <<
"</CTestMeasurement>" << std::endl;
Image Measurements
""""""""""""""""""
The following example demonstrates how to upload test images to CDash.
.. code-block:: c++
std::cout <<
"<CTestMeasurementFile type=\"image/jpg\" name=\"TestImage\">" <<
"/dir/to/test_img.jpg</CTestMeasurementFile>" << std::endl;
std::cout <<
"<CTestMeasurementFile type=\"image/gif\" name=\"ValidImage\">" <<
"/dir/to/valid_img.gif</CTestMeasurementFile>" << std::endl;
std::cout <<
"<CTestMeasurementFile type=\"image/png\" name=\"AlgoResult\">" <<
"/dir/to/img.png</CTestMeasurementFile>"
<< std::endl;
Images will be displayed together in an interactive comparison mode on CDash
if they are provided with two or more of the following names.
* ``TestImage``
* ``ValidImage``
* ``BaselineImage``
* ``DifferenceImage2``
By convention, ``TestImage`` is the image generated by your test, and
``ValidImage`` (or ``BaselineImage``) is basis of comparison used to determine
if the test passed or failed.
If another image name is used it will be displayed by CDash as a static image
separate from the interactive comparison UI.
Attached Files
""""""""""""""
.. versionadded:: 3.21
The following example demonstrates how to upload non-image files to CDash.
.. code-block:: c++
std::cout <<
"<CTestMeasurementFile type=\"file\" name=\"TestInputData1\">" <<
"/dir/to/data1.csv</CTestMeasurementFile>\n" <<
"<CTestMeasurementFile type=\"file\" name=\"TestInputData2\">" <<
"/dir/to/data2.csv</CTestMeasurementFile>" << std::endl;
If the name of the file to upload is known at configure time, you can use the
:prop_test:`ATTACHED_FILES` or :prop_test:`ATTACHED_FILES_ON_FAIL` test
properties instead.
Custom Details
""""""""""""""
.. versionadded:: 3.21
The following example demonstrates how to specify a custom value for the
``Test Details`` field displayed on CDash.
.. code-block:: c++
std::cout <<
"<CTestDetails>My Custom Details Value</CTestDetails>" << std::endl;
.. _`Additional Labels`:
Additional Labels
"""""""""""""""""
.. versionadded:: 3.22
The following example demonstrates how to add additional labels to a test
at runtime.
.. code-block:: c++
std::cout <<
"<CTestLabel>Custom Label 1</CTestLabel>\n" <<
"<CTestLabel>Custom Label 2</CTestLabel>" << std::endl;
Use the :prop_test:`LABELS` test property instead for labels that can be
determined at configure time.
@@ -0,0 +1,63 @@
ctest_update
------------
Perform the :ref:`CTest Update Step` as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_update([SOURCE <source-dir>]
[RETURN_VALUE <result-var>]
[VERSION_ONLY]
[VERSION_OVERRIDE <version>]
[CAPTURE_CMAKE_ERROR <result-var>]
[QUIET])
Update the source tree from version control and record results in
``Update.xml`` for submission with the :command:`ctest_submit` command.
The options are:
``SOURCE <source-dir>``
Specify the source directory. If not given, the
:variable:`CTEST_SOURCE_DIRECTORY` variable is used.
``RETURN_VALUE <result-var>``
Store in the ``<result-var>`` variable the number of files
updated or ``-1`` on error.
``VERSION_ONLY``
.. versionadded:: 4.4
Record the currently checked out revision without updating the source tree to
a different version. This is equivalent to setting the
:variable:`CTEST_UPDATE_VERSION_ONLY` variable.
``VERSION_OVERRIDE <version>``
.. versionadded:: 4.4
Report ``<version>`` as the current revision without querying or updating the
source tree. This is equivalent to setting the
:variable:`CTEST_UPDATE_VERSION_OVERRIDE` variable, and supersedes
``VERSION_ONLY``.
``CAPTURE_CMAKE_ERROR <result-var>``
.. versionadded:: 3.13
Store in the ``<result-var>`` variable ``-1`` if there are any errors running
the command and prevent :manual:`ctest(1)` from returning non-zero if an
error occurs.
``QUIET``
.. versionadded:: 3.3
Suppress any CTest-specific non-error messages that would have otherwise
been printed to the console. CTest will still report
the new revision of the repository and any conflicting files
that were found.
By default, the update follows the version control branch currently checked
out in the source directory. The ``VERSION_ONLY`` and
``VERSION_OVERRIDE`` options instead record revision information without
changing the source tree. See the :ref:`CTest Update Step` documentation
for information about further variables that change the behavior of
``ctest_update()``.
@@ -0,0 +1,27 @@
ctest_upload
------------
Upload files to a dashboard server as a :ref:`Dashboard Client`.
.. code-block:: cmake
ctest_upload(FILES <file>... [QUIET] [CAPTURE_CMAKE_ERROR <result-var>])
The options are:
``FILES <file>...``
Specify a list of files to be sent along with the build results to the
dashboard server.
``CAPTURE_CMAKE_ERROR <result-var>``
.. versionadded:: 3.7
Store in the ``<result-var>`` variable ``-1`` if there are any errors running
the command and prevent :manual:`ctest(1)` from returning non-zero if an
error occurs.
``QUIET``
.. versionadded:: 3.3
Suppress any CTest-specific non-error output that would have been
printed to the console otherwise.
@@ -0,0 +1,115 @@
define_property
---------------
Define and document custom properties.
.. code-block:: cmake
define_property(<GLOBAL | DIRECTORY | TARGET | SOURCE |
TEST | VARIABLE | CACHED_VARIABLE>
PROPERTY <name> [INHERITED]
[BRIEF_DOCS <brief-doc> [<docs>...]]
[FULL_DOCS <full-doc> [<docs>...]]
[INITIALIZE_FROM_VARIABLE <variable>])
Defines one property in a scope for use with the :command:`set_property` and
:command:`get_property` commands. It is mainly useful for defining the way
a property is initialized or inherited. Historically, the command also
associated documentation with a property, but that is no longer considered a
primary use case.
The first argument determines the kind of scope in which the property should
be used. It must be one of the following:
* ``GLOBAL`` - associated with the global namespace.
* ``DIRECTORY`` - associated with one directory.
* ``TARGET`` - associated with one target.
* ``SOURCE`` - associated with one source file.
* ``TEST`` - associated with a test named with :command:`add_test`.
* ``VARIABLE`` - documents a CMake language variable.
* ``CACHED_VARIABLE`` - documents a CMake cache variable.
Note that unlike :command:`set_property` and :command:`get_property` no
actual scope needs to be given; only the kind of scope is important.
The required ``PROPERTY`` option is immediately followed by the name of
the property being defined.
If the ``INHERITED`` option is given, then the :command:`get_property` command
will chain up to the next higher scope when the requested property is not set
in the scope given to the command.
* ``DIRECTORY`` scope chains to its parent directory's scope, continuing the
walk up parent directories until a directory has the property set or there
are no more parents. If still not found at the top level directory, it
chains to the ``GLOBAL`` scope.
* ``TARGET``, ``SOURCE`` and ``TEST`` properties chain to ``DIRECTORY`` scope,
including further chaining up the directories, etc. as needed.
Note that this scope chaining behavior only applies to calls to
:command:`get_property`, :command:`get_directory_property`,
:command:`get_target_property`, :command:`get_source_file_property` and
:command:`get_test_property`. There is no inheriting behavior when *setting*
properties, so using ``APPEND`` or ``APPEND_STRING`` with the
:command:`set_property` command will not consider inherited values when working
out the contents to append to.
The ``BRIEF_DOCS`` and ``FULL_DOCS`` options are followed by strings to be
associated with the property as its brief and full documentation.
CMake does not use this documentation other than making it available to the
project via corresponding options to the :command:`get_property` command.
.. versionchanged:: 3.23
The ``BRIEF_DOCS`` and ``FULL_DOCS`` options are optional.
.. versionadded:: 3.23
The ``INITIALIZE_FROM_VARIABLE`` option specifies a variable from which the
property should be initialized. It can only be used with target properties.
The ``<variable>`` name must end with the property name and must not begin
with ``CMAKE_`` or ``_CMAKE_``. The property name must contain at least one
underscore. It is recommended that the property name have a prefix specific
to the project.
Property Redefinition
^^^^^^^^^^^^^^^^^^^^^
Once a property is defined for a particular type of scope, it cannot be
redefined. Attempts to redefine an existing property by calling
:command:`define_property` with the same scope type and property name
will be silently ignored. Defining the same property name for two different
kinds of scope is valid.
:command:`get_property` can be used to determine whether a property is
already defined for a particular kind of scope, and if so, to examine its
definition. For example:
.. code-block:: cmake
# Initial definition
define_property(TARGET PROPERTY MY_NEW_PROP
BRIEF_DOCS "My new custom property"
)
# Later examination
get_property(my_new_prop_exists
TARGET NONE
PROPERTY MY_NEW_PROP
DEFINED
)
if(my_new_prop_exists)
get_property(my_new_prop_docs
TARGET NONE
PROPERTY MY_NEW_PROP
BRIEF_DOCS
)
# ${my_new_prop_docs} is now set to "My new custom property"
endif()
See Also
^^^^^^^^
* :command:`get_property`
* :command:`set_property`
@@ -0,0 +1,119 @@
discover_tests
--------------
.. versionadded:: 4.4
Register tests with names and properties discovered at test time by
:manual:`ctest(1)`.
.. code-block:: cmake
discover_tests(COMMAND <command> [<arg>...] [COMMAND_EXPAND_LISTS]
[CONFIGURATIONS <config>...]
DISCOVERY_ARGS <arg>...
DISCOVERY_MATCH <regex>
[DISCOVERY_PROPERTIES <key> <value> [<key> <value>]...]
TEST_NAME <replacement>
TEST_ARGS <replacement>...
[TEST_PROPERTIES <key> <replacement> [<key> <replacement>]...]
)
This command configures test discovery rather than defining a single test at
configure time. During test execution, :manual:`ctest(1)` runs the specified
discovery command, parses its output, and registers one or more tests based on
the provided regular expression and replacement strings.
``discover_tests`` options are:
``COMMAND``
Specify the command-line used for test discovery.
The command is executed by :manual:`ctest(1)` at test time (not by CMake at
configure time). With ``DISCOVERY_ARGS`` appended, it must print the list of
available tests in a format matched by ``DISCOVERY_MATCH``.
If ``<command>`` specifies an executable target created by
:command:`add_executable`:
* It will automatically be replaced by the location of the executable
created at build time.
* The target's :prop_tgt:`CROSSCOMPILING_EMULATOR`, if set, will be
used to run the command on the host::
<emulator> <command>
The emulator is used only when
:variable:`cross-compiling <CMAKE_CROSSCOMPILING>`.
* The target's :prop_tgt:`TEST_LAUNCHER`, if set, will be used to launch the
command::
<launcher> <command>
If the :prop_tgt:`CROSSCOMPILING_EMULATOR` is also set, both are used::
<launcher> <emulator> <command>
The command may be specified using
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``COMMAND_EXPAND_LISTS``
Lists in ``COMMAND`` arguments will be expanded, including those created with
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``CONFIGURATIONS``
Restrict the test discovery only to the named configurations.
``DISCOVERY_ARGS``
Additional arguments passed to ``COMMAND`` when performing discovery.
``DISCOVERY_MATCH``
Regular expression used to parse each line produced by the discovery command.
Capturing groups may be referenced by ``TEST_NAME``, ``TEST_ARGS``, and
values in ``TEST_PROPERTIES`` using ``\1``, ``\2``, etc.
``DISCOVERY_PROPERTIES``
Specify properties for the discovery run itself.
``TEST_NAME``
Replacement string used to generate the test name for each discovered test.
It may reference capture groups from ``DISCOVERY_MATCH``.
``TEST_ARGS``
Replacement strings used to generate the arguments passed to the discovered
test. Each argument may reference capture groups from ``DISCOVERY_MATCH``.
``TEST_PROPERTIES``
Specify test properties to set on each discovered test. Values are
replacement strings and may reference capture groups from
``DISCOVERY_MATCH``.
CTest executes the discovery step to obtain the list of tests and then runs
each discovered test using the command-line produced by ``COMMAND`` together
with ``TEST_ARGS``. The pass/fail behavior of each discovered test follows
the usual CTest rules (exit code ``0`` indicates success unless inverted by
the :prop_test:`WILL_FAIL` property). Output written to stdout or stderr is
captured by :manual:`ctest(1)` and only affects the pass/fail status via the
:prop_test:`PASS_REGULAR_EXPRESSION`, :prop_test:`FAIL_REGULAR_EXPRESSION`,
or :prop_test:`SKIP_REGULAR_EXPRESSION` test properties.
Example usage:
.. code-block:: cmake
discover_tests(COMMAND testDriver --exe $<TARGET_FILE:myexe>
DISCOVERY_ARGS --list-tests
DISCOVERY_MATCH "^([^,]+),([^,]+),([^,]+),(.*)$"
TEST_NAME "${PROJECT_NAME}.\\1.\\2"
TEST_ARGS --run-test "\\1.\\2"
TEST_PROPERTIES
PROCESSORS "\\3"
LABELS "\\4"
)
This example configures discovery by running ``testDriver --list-tests``.
For each line of output that matches ``DISCOVERY_MATCH``, a test name is
generated using ``TEST_NAME``, the per-test command-line is generated using
``TEST_ARGS``, and test properties are populated from the remaining capture
groups.
@@ -0,0 +1,13 @@
else
----
Starts the else portion of an if block.
.. code-block:: cmake
else([<condition>])
See the :command:`if` command.
The optional ``<condition>`` argument is supported for backward compatibility
only and is not evaluated.
@@ -0,0 +1,11 @@
elseif
------
Starts an elseif portion of an if block.
.. code-block:: cmake
elseif(<condition>)
See the :command:`if` command, especially for the syntax and logic
of the ``<condition>``.
@@ -0,0 +1,29 @@
enable_language
---------------
Enable languages (CXX/C/OBJC/OBJCXX/Fortran/etc)
.. code-block:: cmake
enable_language(<lang>... [OPTIONAL])
Enables support for the named languages in CMake. This is the same as
the :command:`project` command but does not create any of the extra
variables that are created by the :command:`project` command.
.. include:: include/SUPPORTED_LANGUAGES.rst
The following restrictions apply to where ``enable_language()`` may be called:
* It must be called in file scope, not in a :command:`function` call
nor inside a :command:`block()`.
* It must not be called before the first call to :command:`project`.
See policy :policy:`CMP0165`.
* It must be called in the highest directory common to all targets
using the named language directly for compiling sources or
indirectly through link dependencies. It is simplest to enable all
needed languages in the top-level directory of a project.
The ``OPTIONAL`` keyword is a placeholder for future implementation and
does not currently work. Instead you can use the :module:`CheckLanguage`
module to verify support before enabling.
@@ -0,0 +1,51 @@
enable_testing
--------------
Enables testing for the current directory and below:
.. code-block:: cmake
enable_testing()
This command should be invoked in the top-level source directory because
:manual:`ctest(1)` expects to find a test file in the top-level
build directory.
This command is also automatically invoked when the :module:`CTest`
module is included, except if the :variable:`BUILD_TESTING`
option is turned off.
The following restrictions apply to where ``enable_testing()`` may be called:
* It must be called in file scope, not in a :command:`function` call nor inside
a :command:`block`.
Examples
^^^^^^^^
In the following example, this command is conditionally called depending on how
the project is used. For instance, when the Example project is added via the
:module:`FetchContent` module as a subdirectory of a parent project that defines
its own tests, testing for the Example project is disabled.
.. code-block:: cmake
:caption: ``CMakeLists.txt``
project(Example)
option(Example_ENABLE_TESTING "Enable testing" ${PROJECT_IS_TOP_LEVEL})
if(Example_ENABLE_TESTING)
enable_testing()
endif()
# ...
if(Example_ENABLE_TESTING)
add_test(...)
endif()
See Also
^^^^^^^^
* The :command:`add_test` command.
@@ -0,0 +1,11 @@
endblock
--------
.. versionadded:: 3.25
Ends a list of commands in a :command:`block` and removes the scopes
created by the :command:`block` command.
.. code-block:: cmake
endblock()
@@ -0,0 +1,14 @@
endforeach
----------
Ends a list of commands in a foreach block.
.. code-block:: cmake
endforeach([<loop_var>])
See the :command:`foreach` command.
The optional ``<loop_var>`` argument is supported for backward compatibility
only. If used it must be a verbatim repeat of the ``<loop_var>`` argument of
the opening ``foreach`` clause.
@@ -0,0 +1,14 @@
endfunction
-----------
Ends a list of commands in a function block.
.. code-block:: cmake
endfunction([<name>])
See the :command:`function` command.
The optional ``<name>`` argument is supported for backward compatibility
only. If used it must be a verbatim repeat of the ``<name>`` argument
of the opening ``function`` command.
@@ -0,0 +1,14 @@
endif
-----
Ends a list of commands in an if block.
.. code-block:: cmake
endif([<condition>])
See the :command:`if` command.
The optional ``<condition>`` argument is supported for backward compatibility
only. If used it must be a verbatim repeat of the argument of the opening
``if`` clause.
@@ -0,0 +1,14 @@
endmacro
--------
Ends a list of commands in a macro block.
.. code-block:: cmake
endmacro([<name>])
See the :command:`macro` command.
The optional ``<name>`` argument is supported for backward compatibility
only. If used it must be a verbatim repeat of the ``<name>`` argument
of the opening ``macro`` command.
@@ -0,0 +1,14 @@
endwhile
--------
Ends a list of commands in a while block.
.. code-block:: cmake
endwhile([<condition>])
See the :command:`while` command.
The optional ``<condition>`` argument is supported for backward compatibility
only. If used it must be a verbatim repeat of the argument of the opening
``while`` clause.
@@ -0,0 +1,63 @@
exec_program
------------
.. versionchanged:: 3.28
This command is available only if policy :policy:`CMP0153` is not set to ``NEW``.
Port projects to the :command:`execute_process` command.
.. deprecated:: 3.0
Use the :command:`execute_process` command instead.
Runs an executable program during the processing of a CMake file or script:
.. code-block:: cmake
exec_program(
<executable>
[<working-dir>]
[ARGS <arguments-to-executable>...]
[OUTPUT_VARIABLE <var>]
[RETURN_VALUE <var>]
)
The ``<executable>`` is run in the optionally specified directory
``<working-dir>``. The
executable can include arguments if it is double quoted, but it is
better to use the optional ``ARGS`` argument to specify arguments to the
executable program. This is because CMake will then be able to escape spaces in
the executable path. An optional argument ``OUTPUT_VARIABLE`` specifies a
variable in which to store the output. To capture the return value of
the execution, provide a ``RETURN_VALUE``. If ``OUTPUT_VARIABLE`` is
specified, then no output will go to the stdout/stderr of the console
running CMake.
Examples
^^^^^^^^
Example of the legacy ``exec_program()`` command used in earlier versions of
CMake:
.. code-block:: cmake
exec_program(
some_command
${dir}
ARGS arg_1 arg_2 args "\"<quoted-arg>\""
OUTPUT_VARIABLE output
RETURN_VALUE result
)
A direct equivalent replacement of the previous example using the
:command:`execute_process` command in new code:
.. code-block:: cmake
execute_process(
COMMAND some_command arg_1 arg_2 args "<quoted-arg>"
WORKING_DIRECTORY ${dir}
RESULT_VARIABLE result
OUTPUT_VARIABLE output
ERROR_VARIABLE output
OUTPUT_STRIP_TRAILING_WHITESPACE
)
@@ -0,0 +1,244 @@
execute_process
---------------
Execute one or more child processes.
.. code-block:: cmake
execute_process(COMMAND <cmd1> [<arguments>]
[COMMAND <cmd2> [<arguments>]]...
[WORKING_DIRECTORY <directory>]
[TIMEOUT <seconds>]
[RESULT_VARIABLE <variable>]
[RESULTS_VARIABLE <variable>]
[OUTPUT_VARIABLE <variable>]
[ERROR_VARIABLE <variable>]
[INPUT_FILE <file>]
[OUTPUT_FILE <file>]
[ERROR_FILE <file>]
[OUTPUT_QUIET]
[ERROR_QUIET]
[COMMAND_ECHO <where>]
[OUTPUT_STRIP_TRAILING_WHITESPACE]
[ERROR_STRIP_TRAILING_WHITESPACE]
[ENCODING <name>]
[ENVIRONMENT <variable=value>...]
[ENVIRONMENT_MODIFICATION <env-mod-op>...]
[ECHO_OUTPUT_VARIABLE]
[ECHO_ERROR_VARIABLE]
[COMMAND_ERROR_IS_FATAL <ANY|LAST|NONE>])
Runs the given sequence of one or more commands.
Commands are executed concurrently as a pipeline, with the standard
output of each process piped to the standard input of the next.
A single standard error pipe is used for all processes.
``execute_process`` runs commands while CMake is configuring the project,
prior to build system generation. Use the :command:`add_custom_target` and
:command:`add_custom_command` commands to create custom commands that run
at build time.
Options:
``COMMAND``
A child process command line.
CMake executes the child process using operating system APIs directly:
* On POSIX platforms, the command line is passed to the child process
in an ``argv[]`` style array. No intermediate shell is executed,
so shell operators such as ``>`` are treated as normal arguments.
* On Windows platforms, the command line is encoded as a string such
that child processes using `CommandLineToArgvW`_ will decode the
original arguments.
If the command runs a ``.exe``, ``.com``, or other executable,
no intermediate command interpreter is executed, so shell operators
such as ``>`` are treated as normal arguments.
If the command runs a ``.bat`` or ``.cmd`` script, it is executed
through the ``cmd`` command interpreter. The command interpreter
does not use `CommandLineToArgvW`_, so some arguments may be received
by the script with extra quoting.
.. versionchanged:: 4.0
``.bat`` and ``.cmd`` scripts are now explicitly executed through the
command interpreter by prepending ``cmd /c call`` to the command line.
Previously, they were implicitly executed through ``cmd /c``, without
``call``, by undocumented behavior of `CreateProcessW`_.
Use the ``INPUT_*``, ``OUTPUT_*``, and ``ERROR_*`` options to
redirect stdin, stdout, and stderr.
For **sequential execution** of multiple commands use multiple
``execute_process`` calls each with a single ``COMMAND`` argument.
``WORKING_DIRECTORY``
The named directory will be set as the current working directory of
the child processes. If not given, the child processes' working directory is
unspecified.
``TIMEOUT``
After the specified number of seconds (fractions allowed), all unfinished
child processes will be terminated, and the ``RESULT_VARIABLE`` will be
set to a string mentioning the "timeout".
``RESULT_VARIABLE``
The variable will be set to contain the result of last child process.
This will be an integer return code from the last child or a string
describing an error condition.
``RESULTS_VARIABLE <variable>``
.. versionadded:: 3.10
The variable will be set to contain the result of all processes as a
:ref:`semicolon-separated list <CMake Language Lists>`, in order of the
given ``COMMAND`` arguments. Each entry will be an integer return code
from the corresponding child or a string describing an error condition.
``INPUT_FILE <file>``
``<file>`` is attached to the standard input pipe of the *first* ``COMMAND``
process.
``OUTPUT_FILE <file>``
``<file>`` is attached to the standard output pipe of the *last* ``COMMAND``
process.
``ERROR_FILE <file>``
``<file>`` is attached to the standard error pipe of *all* ``COMMAND``
processes.
.. versionadded:: 3.3
If the same ``<file>`` is named for both ``OUTPUT_FILE`` and ``ERROR_FILE``
then it will be used for both standard output and standard error pipes.
``OUTPUT_QUIET``, ``ERROR_QUIET``
The standard output on ``OUTPUT_VARIABLE`` or standard error on
``ERROR_VARIABLE`` are not connected (no variable content).
The ``*_FILE`` and ``ECHO_*_VARIABLE`` options are not affected.
``OUTPUT_VARIABLE``, ``ERROR_VARIABLE``
The variable named will be set with the contents of the standard output
and standard error pipes, respectively. If the same variable is named
for both pipes their output will be merged in the order produced.
``OUTPUT_STRIP_TRAILING_WHITESPACE``, ``ERROR_STRIP_TRAILING_WHITESPACE``
Removes whitespace characters from the end of the values stored in the
corresponding ``OUTPUT_VARIABLE`` and ``ERROR_VARIABLE`` variables.
``ECHO_OUTPUT_VARIABLE``, ``ECHO_ERROR_VARIABLE``
.. versionadded:: 3.18
The standard output or standard error will not be exclusively redirected to
the specified variables.
The output will be duplicated into the specified variables and also onto
standard output or standard error analogous to the ``tee`` Unix command.
.. note::
If more than one ``OUTPUT_*`` or ``ERROR_*`` option is given for the
same pipe the precedence is *not specified*.
If no ``OUTPUT_*`` or ``ERROR_*`` options are given the output will
be shared with the corresponding pipes of the CMake process itself.
``COMMAND_ECHO <where>``
.. versionadded:: 3.15
The command being run will be echo'ed to ``<where>`` with ``<where>``
being set to one of ``STDERR``, ``STDOUT`` or ``NONE``.
See the :variable:`CMAKE_EXECUTE_PROCESS_COMMAND_ECHO` variable for a way
to control the default behavior when this option is not present.
``ENCODING <name>``
.. versionadded:: 3.8
On Windows, the encoding that is used to decode output from the process.
Ignored on other platforms.
Valid encoding names are:
``NONE``
Perform no decoding. This assumes that the process output is encoded
in the same way as CMake's internal encoding (UTF-8).
This was the default in CMake 3.14 and older.
``AUTO``
Use the current active console's codepage or if that isn't
available then use ANSI.
This was the default in CMake 3.15 through 3.30.
``ANSI``
Use the ANSI codepage.
``OEM``
Use the original equipment manufacturer (OEM) code page.
``UTF-8``
.. versionadded:: 3.11
Use the UTF-8 codepage.
This is the default since CMake 3.31. See policy :policy:`CMP0176`.
``UTF8``
Use the UTF-8 codepage. Use of this name is discouraged in favor
of ``UTF-8`` to match the
`UTF-8 RFC <https://datatracker.ietf.org/doc/html/rfc3629>`_
naming convention.
``ENVIRONMENT <variable=value>...``
.. versionadded:: 4.4
Add environment variable definitions to the environment of the child
processes. Each entry must be of the form ``NAME=value`` and is interpreted
as setting ``NAME`` to ``value`` for the duration of the
``execute_process()`` call.
These entries are processed in order. If the same variable name is given
multiple times, the last value wins.
``ENVIRONMENT_MODIFICATION <env-mod-op>...``
.. versionadded:: 4.4
Apply one or more :prop_test:`ENVIRONMENT_MODIFICATION` operations to the
environment of the child processes. Each operation is applied in the given
order, and failures to parse an operation are treated as errors.
Environment modifications are applied after ``ENVIRONMENT`` entries, if both
options are specified.
``COMMAND_ERROR_IS_FATAL <ANY|LAST|NONE>``
.. versionadded:: 3.19
The option following ``COMMAND_ERROR_IS_FATAL`` determines the behavior when
an error is encountered:
``ANY``
If any of the commands in the list of commands fail, the
``execute_process()`` command halts with an error.
``LAST``
If the last command in the list of commands fails, the
``execute_process()`` command halts with an error.
Commands earlier in the list will not cause a fatal error.
``NONE``
.. versionadded:: 4.0
Regardless of any of the commands failing, the ``execute_process()``
command will not halt with an error.
.. versionadded:: 4.0
If not provided, the
:variable:`CMAKE_EXECUTE_PROCESS_COMMAND_ERROR_IS_FATAL` variable
is checked. If the variable is not set, the default is ``NONE``.
If ``RESULT_VARIABLE`` or ``RESULTS_VARIABLE`` is supplied,
:variable:`CMAKE_EXECUTE_PROCESS_COMMAND_ERROR_IS_FATAL` is ignored.
.. _`CommandLineToArgvW`: https://learn.microsoft.com/en-us/windows/win32/api/shellapi/nf-shellapi-commandlinetoargvw
.. _`CreateProcessW`: https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessw
@@ -0,0 +1,296 @@
export
------
Export targets or packages for outside projects to use them directly
from the current project's build tree, without installation.
See the :command:`install(EXPORT)` command to export targets from an
install tree.
Synopsis
^^^^^^^^
.. parsed-literal::
export(`TARGETS`_ <target>... [...])
export(`EXPORT`_ <export-name> [...])
export(`PACKAGE`_ <PackageName>)
export(`SETUP`_ <export-name> [...])
export(`PACKAGE_INFO`_ <package-name> [...])
export(`SBOM`_ <sbom-name> [...])
Exporting Targets
^^^^^^^^^^^^^^^^^
.. signature::
export(TARGETS <target>... [...])
.. code-block:: cmake
export(TARGETS <target>... [NAMESPACE <namespace>]
[APPEND] FILE <filename> [EXPORT_LINK_INTERFACE_LIBRARIES]
[CXX_MODULES_DIRECTORY <directory>])
Creates a file ``<filename>`` that may be included by outside projects to
import targets named by ``<target>...`` from the current project's build tree.
This is useful during cross-compiling to build utility executables that can
run on the host platform in one project and then import them into another
project being compiled for the target platform.
The file created by this command is specific to the build tree and
should never be installed. See the :command:`install(EXPORT)` command to
export targets from an install tree.
The options are:
``NAMESPACE <namespace>``
Prepend the ``<namespace>`` string to all target names written to the file.
``APPEND``
Append to the file instead of overwriting it. This can be used to
incrementally export multiple targets to the same file.
``EXPORT_LINK_INTERFACE_LIBRARIES``
Include the contents of the properties named with the pattern
``(IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)?``
in the export, even when policy :policy:`CMP0022` is NEW. This is useful
to support consumers using CMake versions older than 2.8.12.
``CXX_MODULES_DIRECTORY <directory>``
.. versionadded:: 3.28
Export C++ module properties to files under the given directory. Each file
will be named according to the target's export name (without any namespace).
These files will automatically be included from the export file.
This signature requires all targets to be listed explicitly. If a library
target is included in the export, but a target to which it links is not
included, the behavior is unspecified. See the :command:`export(EXPORT)` signature
to automatically export the same targets from the build tree as
:command:`install(EXPORT)` would from an install tree.
.. note::
:ref:`Object Libraries` under :generator:`Xcode` have special handling if
multiple architectures are listed in :variable:`CMAKE_OSX_ARCHITECTURES`.
In this case they will be exported as :ref:`Interface Libraries` with
no object files available to clients. This is sufficient to satisfy
transitive usage requirements of other targets that link to the
object libraries in their implementation.
This command exports all :ref:`build configurations` from the build tree.
See the :variable:`CMAKE_MAP_IMPORTED_CONFIG_<CONFIG>` variable to map
configurations of dependent projects to the exported configurations.
Exporting Targets to Android.mk
"""""""""""""""""""""""""""""""
.. code-block:: cmake
export(TARGETS <target>... ANDROID_MK <filename>)
.. versionadded:: 3.7
This signature exports CMake built targets to the android ndk build system
by creating an ``Android.mk`` file that references the prebuilt targets. The
Android NDK supports the use of prebuilt libraries, both static and shared.
This allows CMake to build the libraries of a project and make them available
to an ndk build system complete with transitive dependencies, include flags
and defines required to use the libraries. The signature takes a list of
targets and puts them in the ``Android.mk`` file specified by the
``<filename>`` given. This signature can only be used if policy
:policy:`CMP0022` is NEW for all targets given. A error will be issued if
that policy is set to OLD for one of the targets.
Exporting Targets matching install(EXPORT)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. signature::
export(EXPORT <export-name> [...])
.. code-block:: cmake
export(EXPORT <export-name> [NAMESPACE <namespace>] [FILE <filename>]
[CXX_MODULES_DIRECTORY <directory>] [EXPORT_PACKAGE_DEPENDENCIES])
Creates a file ``<filename>`` that may be included by outside projects to
import targets from the current project's build tree. This is the same
as the :command:`export(TARGETS)` signature, except that the targets are not
explicitly listed. Instead, it exports the targets associated with
the installation export ``<export-name>``. Target installations may be
associated with the export ``<export-name>`` using the ``EXPORT`` option
of the :command:`install(TARGETS)` command.
``EXPORT_PACKAGE_DEPENDENCIES``
.. note::
Experimental. Gated by ``CMAKE_EXPERIMENTAL_EXPORT_PACKAGE_DEPENDENCIES``.
Specify that :command:`find_dependency` calls should be exported. See
:command:`install(EXPORT)` for details on how this works.
Exporting Targets to the |CPS|
""""""""""""""""""""""""""""""
.. signature::
export(PACKAGE_INFO <package-name> [...])
.. code-block:: cmake
export(PACKAGE_INFO <package-name> EXPORT <export-name>
[PROJECT <project-name>|NO_PROJECT_METADATA]
[APPENDIX <appendix-name>]
[LOWER_CASE_FILE]
[VERSION <version>
[COMPAT_VERSION <version>]
[VERSION_SCHEMA <string>]]
[DEFAULT_TARGETS <target>...]
[DEFAULT_CONFIGURATIONS <config>...]
[LICENSE <license-string>]
[DEFAULT_LICENSE <license-string>]
[DESCRIPTION <description-string>]
[HOMEPAGE_URL <url-string>]
[CXX_MODULES_DIRECTORY <directory>])
.. versionadded:: 4.3
Creates a file in the |CPS|_ that may be included by outside projects to import
targets named by ``<target>...`` from the current project's build tree. See
the :command:`install(PACKAGE_INFO)` command to export targets from an install
tree. The imported targets are implicitly in the namespace ``<package-name>``.
The default file name is ``<package-name>[-<appendix-name>].cps``. If the
``LOWER_CASE_FILE`` option is given, the file name will use the package name
converted to lower case. Files are written to the ``cps/<package-name>``
subdirectory of the current build directory.
See :command:`install(PACKAGE_INFO)` for a description of the other options.
Exporting Software Bill of Materials (SBOM) Documents
"""""""""""""""""""""""""""""""""""""""""""""""""""""
.. signature::
export(SBOM <sbom-name> [...])
.. code-block:: cmake
export(SBOM <sbom-name> EXPORTS <export-names>...
[FORMAT <string>]
[PROJECT <project-name>|NO_PROJECT_METADATA]
[VERSION <major>[.<minor>[.<patch>[.<tweak>]]]]
[LICENSE <license-string>]
[DESCRIPTION <description-string>]
[HOMEPAGE_URL <url-string>]
[PACKAGE_URL <url-string>])
.. versionadded:: 4.3
.. note::
Experimental. Gated by ``CMAKE_EXPERIMENTAL_GENERATE_SBOM``.
Generates a software bill of materials (SBOM) document describing the targets
in the listed ``<export-names>`` export sets and their dependencies in the
build tree. Targets from all listed exports are aggregated into one document.
The generated SBOM will be written to the ``sbom/<sbom-name>`` subdirectory of
the current build directory.
See :command:`install(SBOM)` for details about the supported SBOM formats and a
description of the other options.
Exporting Packages
^^^^^^^^^^^^^^^^^^
.. signature::
export(PACKAGE <PackageName>)
.. code-block:: cmake
export(PACKAGE <PackageName>)
Store the current build directory in the CMake user package registry
for package ``<PackageName>``. The :command:`find_package` command may consider the
directory while searching for package ``<PackageName>``. This helps dependent
projects find and use a package from the current project's build tree
without help from the user. Note that the entry in the package
registry that this command creates works only in conjunction with a
package configuration file (``<PackageName>Config.cmake``) that works with the
build tree. In some cases, for example for packaging and for system
wide installations, it is not desirable to write the user package
registry.
.. versionchanged:: 3.1
If the :variable:`CMAKE_EXPORT_NO_PACKAGE_REGISTRY` variable
is enabled, the ``export(PACKAGE)`` command will do nothing.
.. versionchanged:: 3.15
By default the ``export(PACKAGE)`` command does nothing (see policy
:policy:`CMP0090`) because populating the user package registry has effects
outside the source and build trees. Set the
:variable:`CMAKE_EXPORT_PACKAGE_REGISTRY` variable to add build directories
to the CMake user package registry.
Configuring Exports
^^^^^^^^^^^^^^^^^^^
.. signature::
export(SETUP <export-name> [...])
.. code-block:: cmake
export(SETUP <export-name>
[PACKAGE_DEPENDENCY <dep>
[ENABLED (<bool-true>|<bool-false>|AUTO)]
[EXTRA_ARGS <args>...]
] [...]
[TARGET <target>
[XCFRAMEWORK_LOCATION <location>]
] [...]
)
.. versionadded:: 3.29
Configure the parameters of an export. The arguments are as follows:
``PACKAGE_DEPENDENCY <dep>``
.. note::
Experimental. Gated by ``CMAKE_EXPERIMENTAL_EXPORT_PACKAGE_DEPENDENCIES``.
Specify a package dependency to configure. This changes how
:command:`find_dependency` calls are written during
:command:`export(EXPORT)` and :command:`install(EXPORT)`. ``<dep>`` is the
name of a package to export. This argument accepts the following additional
arguments:
``ENABLED``
Manually control whether or not the dependency is exported. This accepts
the following values:
``<bool-true>``
Any value that CMake recognizes as "true". Always export the dependency,
even if no exported targets depend on it. This can be used to manually
add :command:`find_dependency` calls to the export.
``<bool-false>``
Any value that CMake recognizes as "false". Never export the dependency,
even if an exported target depends on it.
``AUTO``
Only export the dependency if an exported target depends on it.
``EXTRA_ARGS <args>``
Specify additional arguments to pass to :command:`find_dependency` after
the ``REQUIRED`` argument.
``TARGET <target>``
Specify a target to configure in this export. This argument accepts the
following additional arguments:
``XCFRAMEWORK_LOCATION``
Specify the location of an ``.xcframework`` which contains the library from
this target. If specified, the generated code will check to see if the
``.xcframework`` exists, and if it does, it will use the ``.xcframework``
as its imported location instead of the installed library.
.. _CPS: https://cps-org.github.io/cps/
.. |CPS| replace:: Common Package Specification
@@ -0,0 +1,28 @@
export_library_dependencies
---------------------------
Disallowed since version 3.0. See CMake Policy :policy:`CMP0033`.
Use :command:`install(EXPORT)` or :command:`export` command.
This command generates an old-style library dependencies file.
Projects requiring CMake 2.6 or later should not use the command. Use
instead the :command:`install(EXPORT)` command to help export targets from an
installation tree and the :command:`export` command to export targets from a
build tree.
The old-style library dependencies file does not take into account
per-configuration names of libraries or the
:prop_tgt:`LINK_INTERFACE_LIBRARIES` target property.
.. code-block:: cmake
export_library_dependencies(<file> [APPEND])
Create a file named ``<file>`` that can be included into a CMake listfile
with the INCLUDE command. The file will contain a number of SET
commands that will set all the variables needed for library dependency
information. This should be the last command in the top level
CMakeLists.txt file of the project. If the ``APPEND`` option is
specified, the SET commands will be appended to the given file instead
of replacing it.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,48 @@
find_file
---------
.. |FIND_XXX| replace:: find_file
.. |NAMES| replace:: NAMES <name>...
.. |SEARCH_XXX| replace:: full path to a file
.. |SEARCH_XXX_DESC| replace:: full path to a named file
.. |prefix_XXX_SUBDIR| replace:: ``<prefix>/include``
.. |entry_XXX_SUBDIR| replace:: ``<entry>/include``
.. |FIND_XXX_REGISTRY_VIEW_DEFAULT| replace:: ``TARGET``
.. |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX| replace::
``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE`
is set, and |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX_SUBDIR|
.. |CMAKE_PREFIX_PATH_XXX| replace::
``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE`
is set, and |CMAKE_PREFIX_PATH_XXX_SUBDIR|
.. |CMAKE_XXX_PATH| replace:: :variable:`CMAKE_INCLUDE_PATH`
.. |CMAKE_XXX_MAC_PATH| replace:: :variable:`CMAKE_FRAMEWORK_PATH`
.. |ENV_CMAKE_PREFIX_PATH_XXX| replace::
``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set,
and |ENV_CMAKE_PREFIX_PATH_XXX_SUBDIR|
.. |ENV_CMAKE_XXX_PATH| replace:: :envvar:`CMAKE_INCLUDE_PATH`
.. |ENV_CMAKE_XXX_MAC_PATH| replace:: :envvar:`CMAKE_FRAMEWORK_PATH`
.. |SYSTEM_ENVIRONMENT_PATH_XXX| replace:: The directories in ``INCLUDE``
and ``PATH``.
.. |SYSTEM_ENVIRONMENT_PATH_WINDOWS_XXX| replace::
On Windows hosts, CMake 3.3 through 3.27 searched additional paths:
``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE`
is set, and |SYSTEM_ENVIRONMENT_PREFIX_PATH_XXX_SUBDIR|.
This behavior was removed by CMake 3.28.
.. |CMAKE_SYSTEM_PREFIX_PATH_XXX| replace::
``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE`
is set, and |CMAKE_SYSTEM_PREFIX_PATH_XXX_SUBDIR|
.. |CMAKE_SYSTEM_XXX_PATH| replace::
:variable:`CMAKE_SYSTEM_INCLUDE_PATH`
.. |CMAKE_SYSTEM_XXX_MAC_PATH| replace::
:variable:`CMAKE_SYSTEM_FRAMEWORK_PATH`
.. |CMAKE_FIND_ROOT_PATH_MODE_XXX| replace::
:variable:`CMAKE_FIND_ROOT_PATH_MODE_INCLUDE`
.. include:: include/FIND_XXX.rst
@@ -0,0 +1,98 @@
find_library
------------
.. |FIND_XXX| replace:: find_library
.. |NAMES| replace:: NAMES <name>... [NAMES_PER_DIR]
.. |SEARCH_XXX| replace:: library
.. |SEARCH_XXX_DESC| replace:: library
.. |prefix_XXX_SUBDIR| replace:: ``<prefix>/lib``
.. |entry_XXX_SUBDIR| replace:: ``<entry>/lib``
.. |FIND_XXX_REGISTRY_VIEW_DEFAULT| replace:: ``TARGET``
.. |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX| replace::
``<prefix>/lib/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set,
and |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX_SUBDIR|
.. |CMAKE_PREFIX_PATH_XXX| replace::
``<prefix>/lib/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set,
and |CMAKE_PREFIX_PATH_XXX_SUBDIR|
.. |CMAKE_XXX_PATH| replace:: :variable:`CMAKE_LIBRARY_PATH`
.. |CMAKE_XXX_MAC_PATH| replace:: :variable:`CMAKE_FRAMEWORK_PATH`
.. |ENV_CMAKE_PREFIX_PATH_XXX| replace::
``<prefix>/lib/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set,
and |ENV_CMAKE_PREFIX_PATH_XXX_SUBDIR|
.. |ENV_CMAKE_XXX_PATH| replace:: :envvar:`CMAKE_LIBRARY_PATH`
.. |ENV_CMAKE_XXX_MAC_PATH| replace:: :envvar:`CMAKE_FRAMEWORK_PATH`
.. |SYSTEM_ENVIRONMENT_PATH_XXX| replace:: The directories in ``LIB``
and ``PATH``.
.. |SYSTEM_ENVIRONMENT_PATH_WINDOWS_XXX| replace::
On Windows hosts, CMake 3.3 through 3.27 searched additional paths:
``<prefix>/lib/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE`
is set, and |SYSTEM_ENVIRONMENT_PREFIX_PATH_XXX_SUBDIR|.
This behavior was removed by CMake 3.28.
.. |CMAKE_SYSTEM_PREFIX_PATH_XXX| replace::
``<prefix>/lib/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE` is set,
and |CMAKE_SYSTEM_PREFIX_PATH_XXX_SUBDIR|
.. |CMAKE_SYSTEM_XXX_PATH| replace::
:variable:`CMAKE_SYSTEM_LIBRARY_PATH`
.. |CMAKE_SYSTEM_XXX_MAC_PATH| replace::
:variable:`CMAKE_SYSTEM_FRAMEWORK_PATH`
.. |CMAKE_FIND_ROOT_PATH_MODE_XXX| replace::
:variable:`CMAKE_FIND_ROOT_PATH_MODE_LIBRARY`
.. include:: include/FIND_XXX.rst
When more than one value is given to the ``NAMES`` option this command by
default will consider one name at a time and search every directory
for it. The ``NAMES_PER_DIR`` option tells this command to consider one
directory at a time and search for all names in it.
Each library name given to the ``NAMES`` option is first considered
as is, if it contains a library suffix, and then considered with
platform-specific prefixes (e.g. ``lib``) and suffixes (e.g. ``.so``),
as defined by the variables :variable:`CMAKE_FIND_LIBRARY_PREFIXES` and
:variable:`CMAKE_FIND_LIBRARY_SUFFIXES`. Therefore one
may specify library file names such as ``libfoo.a`` directly.
This can be used to locate static libraries on UNIX-like systems.
If the library found is a framework, then ``<VAR>`` will be set to the full
path to the framework ``<fullPath>/A.framework``. When a full path to a
framework is used as a library, CMake will use a ``-framework A``, and a
``-F<fullPath>`` to link the framework to the target.
.. versionadded:: 3.28
The library found can now be a ``.xcframework`` folder.
If the :variable:`CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX` variable is set all
search paths will be tested as normal, with the suffix appended, and with
all matches of ``lib/`` replaced with
``lib${CMAKE_FIND_LIBRARY_CUSTOM_LIB_SUFFIX}/``. This variable overrides
the :prop_gbl:`FIND_LIBRARY_USE_LIB32_PATHS`,
:prop_gbl:`FIND_LIBRARY_USE_LIBX32_PATHS`,
and :prop_gbl:`FIND_LIBRARY_USE_LIB64_PATHS` global properties.
If the :prop_gbl:`FIND_LIBRARY_USE_LIB32_PATHS` global property is set
all search paths will be tested as normal, with ``32/`` appended, and
with all matches of ``lib/`` replaced with ``lib32/``. This property is
automatically set for the platforms that are known to need it if at
least one of the languages supported by the :command:`project` command
is enabled.
If the :prop_gbl:`FIND_LIBRARY_USE_LIBX32_PATHS` global property is set
all search paths will be tested as normal, with ``x32/`` appended, and
with all matches of ``lib/`` replaced with ``libx32/``. This property is
automatically set for the platforms that are known to need it if at
least one of the languages supported by the :command:`project` command
is enabled.
If the :prop_gbl:`FIND_LIBRARY_USE_LIB64_PATHS` global property is set
all search paths will be tested as normal, with ``64/`` appended, and
with all matches of ``lib/`` replaced with ``lib64/``. This property is
automatically set for the platforms that are known to need it if at
least one of the languages supported by the :command:`project` command
is enabled.
File diff suppressed because it is too large. Load diff
Loaded 100 of 9122 files, more files were not shown because too many files have changed in this diff. Show more