merge upstream 3.25.1

This commit is contained in:
denghao 2023-04-04 10:35:44 +08:00
parent 7ec12ed663
commit a44cced353
12005 changed files with 435367 additions and 290965 deletions

View File

@ -20,9 +20,13 @@ SortUsingDeclarations: false
SpaceAfterTemplateKeyword: true
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^[<"]cmSTL\.hxx'
Priority: -2
- Regex: '^[<"]cmConfigure\.h'
Priority: -1
- Regex: '^(<|")cm/'
- Regex: '^<queue>'
Priority: 1
- Regex: '^(<|")cm(ext)?/'
Priority: 2
- Regex: '^(<|")windows\.h'
Priority: 3
@ -30,16 +34,18 @@ IncludeCategories:
Priority: 5
- Regex: '^(<|")Qt?[A-Z]'
Priority: 6
- Regex: '^(<|")cmsys/'
- Regex: '^<cmtp/'
Priority: 7
- Regex: '^(<|")cm_'
- Regex: '^(<|")cmsys/'
Priority: 8
- Regex: '^(<|")cm[A-Z][^.]+\.h'
- Regex: '^(<|")cm_'
Priority: 9
- Regex: '^(<|")cm[A-Z][^.]+\.h'
Priority: 10
- Regex: '^<[^.]+\.h'
Priority: 4
- Regex: '^<'
Priority: 1
- Regex: '.*'
Priority: 10
Priority: 11
...

View File

@ -1,28 +1,37 @@
---
Checks: "-*,\
bugprone-*,\
-bugprone-easily-swappable-parameters,\
-bugprone-implicit-widening-of-multiplication-result,\
-bugprone-macro-parentheses,\
-bugprone-misplaced-widening-cast,\
-bugprone-narrowing-conversions,\
-bugprone-too-small-loop-variable,\
google-readability-casting,\
misc-*,\
-misc-no-recursion,\
-misc-non-private-member-variables-in-classes,\
-misc-static-assert,\
modernize-*,\
-modernize-avoid-c-arrays,\
-modernize-return-braced-init-list,\
-modernize-use-nodiscard,\
-modernize-use-noexcept,\
-modernize-use-trailing-return-type,\
-modernize-use-transparent-functors,\
performance-*,\
readability-*,\
-readability-convert-member-functions-to-static,\
-readability-function-cognitive-complexity,\
-readability-function-size,\
-readability-identifier-length,\
-readability-identifier-naming,\
-readability-implicit-bool-conversion,\
-readability-inconsistent-declaration-parameter-name,\
-readability-magic-numbers,\
-readability-named-parameter,\
-readability-redundant-declaration,\
-readability-redundant-member-init,\
-readability-suspicious-call-argument,\
-readability-uppercase-literal-suffix,\
"
HeaderFilterRegex: 'Source/cm[^/]*\.(h|hxx|cxx)$'

View File

@ -1,4 +1,16 @@
install(DIRECTORY vim/indent vim/syntax DESTINATION ${CMAKE_DATA_DIR}/editors/vim)
install(FILES cmake-mode.el DESTINATION ${CMAKE_DATA_DIR}/editors/emacs)
# Install Vim files to a typical system integration directory.
# Packagers can set CMake_INSTALL_VIMFILES_DIR to control this.
if(NOT CMake_INSTALL_VIMFILES_DIR)
set(CMake_INSTALL_VIMFILES_DIR ${CMAKE_XDGDATA_DIR}/vim/vimfiles)
endif()
install(DIRECTORY vim/indent vim/syntax DESTINATION ${CMake_INSTALL_VIMFILES_DIR})
# Install Emacs files to a typical system integration directory.
# Packagers can set CMake_INSTALL_EMACS_DIR to control this.
if(NOT CMake_INSTALL_EMACS_DIR)
set(CMake_INSTALL_EMACS_DIR ${CMAKE_XDGDATA_DIR}/emacs/site-lisp)
endif()
install(FILES cmake-mode.el DESTINATION ${CMake_INSTALL_EMACS_DIR})
install(FILES cmake.m4 DESTINATION ${CMAKE_XDGDATA_DIR}/aclocal)
add_subdirectory (bash-completion)

View File

@ -1,8 +1,21 @@
# Always install completion file in local dir
# in order to be sure to always be able to install
# in a local user directory rooted in a single directory.
# packager should either patch that out or
# add symlinks to the files in appropriate places
# /etc/bash_completion.d/
# DATADIR/completions (may be /usr/share/<package>/completions
install(FILES cmake cpack ctest DESTINATION ${CMAKE_DATA_DIR}/completions)
# We need to integrate into the system install, or this will silently fail to
# accomplish anything at all, and packagers won't even know it exists. Use the
# `<sharedir>/bash-completion/completions/` hierarchy by default, rooted in
# CMake's XDGDATA_DIR definition of the sharedir. This works with installation
# to `/usr` or `/usr/local` (or any prefix which bash-completion is configured
# with) as well as a simple installation by a local user into their home
# directory *if* the prefix is `$HOME/.local` since `.local/share/` is part of
# the bash-completion search path too.
# For more complex installations, packagers can set CMake_INSTALL_BASH_COMP_DIR
# to another system location.
if(NOT CMake_INSTALL_BASH_COMP_DIR)
if(CMAKE_BASH_COMP_DIR)
# Honor previous customization option.
set(CMake_INSTALL_BASH_COMP_DIR "${CMAKE_BASH_COMP_DIR}")
else()
# Default.
set(CMake_INSTALL_BASH_COMP_DIR ${CMAKE_XDGDATA_DIR}/bash-completion/completions)
endif()
endif()
install(FILES cmake cpack ctest DESTINATION ${CMake_INSTALL_BASH_COMP_DIR})

View File

@ -96,7 +96,15 @@ _cmake()
_filedir
return
;;
--build|--install|--open)
--build)
# Seed the reply with non-directory arguments that we know are
# allowed to follow --build. _filedir will then prepend any valid
# directory matches to these.
COMPREPLY=( $( compgen -W "--preset --list-presets" -- "$cur" ) )
_filedir -d
return
;;
--install|--open)
_filedir -d
return
;;
@ -149,6 +157,34 @@ _cmake()
2>/dev/null | grep -v "^cmake version " )' -- "$cur" ) )
return
;;
--list-presets)
local IFS=$'\n'
local quoted
printf -v quoted %q "$cur"
if [[ ! "${IFS}${COMP_WORDS[*]}${IFS}" =~ "${IFS}--build${IFS}" ]]; then
COMPREPLY=( $( compgen -W "configure${IFS}build${IFS}test${IFS}all" -- "$quoted" ) )
fi
return
;;
--preset)
local IFS=$'\n'
local quoted
printf -v quoted %q "$cur"
local build_or_configure="configure"
if [[ "${IFS}${COMP_WORDS[*]}${IFS}" =~ "${IFS}--build${IFS}" ]]; then
build_or_configure="build"
fi
local presets=$( cmake --list-presets="$build_or_configure" 2>/dev/null |
grep -o "^ \".*\"" | sed \
-e "s/^ //g" \
-e "s/\"//g" \
-e 's/ /\\\\ /g' )
COMPREPLY=( $( compgen -W "$presets" -- "$quoted" ) )
return
;;
esac
$split && return

View File

@ -103,6 +103,17 @@ _ctest()
2>/dev/null | grep -v "^ctest version " )' -- "$cur" ) )
return
;;
--preset)
local IFS=$'\n'
local quoted
printf -v quoted %q "$cur"
COMPREPLY=( $( compgen -W '$( ctest --list-presets 2>/dev/null |
grep -o "^ \".*\"" | sed \
-e "s/^ //g" \
-e "s/\"//g" \
-e "s/ /\\\\ /g" )' -- "$quoted" ) )
return
;;
esac
if [[ "$cur" == -* ]]; then

View File

@ -27,6 +27,9 @@
;; cmake-command-help Written by James Bigler
;;
(require 'rst)
(require 'rx)
(defcustom cmake-mode-cmake-executable "cmake"
"*The name of the cmake executable.
@ -38,8 +41,8 @@ set the path with these commands:
:group 'cmake)
;; Keywords
(defconst cmake-keywords-block-open '("IF" "MACRO" "FOREACH" "ELSE" "ELSEIF" "WHILE" "FUNCTION"))
(defconst cmake-keywords-block-close '("ENDIF" "ENDFOREACH" "ENDMACRO" "ELSE" "ELSEIF" "ENDWHILE" "ENDFUNCTION"))
(defconst cmake-keywords-block-open '("BLOCK" "IF" "MACRO" "FOREACH" "ELSE" "ELSEIF" "WHILE" "FUNCTION"))
(defconst cmake-keywords-block-close '("ENDBLOCK" "ENDIF" "ENDFOREACH" "ENDMACRO" "ELSE" "ELSEIF" "ENDWHILE" "ENDFUNCTION"))
(defconst cmake-keywords
(let ((kwds (append cmake-keywords-block-open cmake-keywords-block-close nil)))
(delete-dups kwds)))
@ -50,6 +53,9 @@ set the path with these commands:
(defconst cmake-regex-comment "#.*")
(defconst cmake-regex-paren-left "(")
(defconst cmake-regex-paren-right ")")
(defconst cmake-regex-closing-parens-line (concat "^[[:space:]]*\\("
cmake-regex-paren-right
"+\\)[[:space:]]*$"))
(defconst cmake-regex-argument-quoted
(rx ?\" (* (or (not (any ?\" ?\\)) (and ?\\ anything))) ?\"))
(defconst cmake-regex-argument-unquoted
@ -71,6 +77,8 @@ set the path with these commands:
(defconst cmake-regex-close
(rx-to-string `(and bol (* space) (regexp ,cmake-regex-block-close)
(* space) (regexp ,cmake-regex-paren-left))))
(defconst cmake-regex-token-paren-left (concat "^" cmake-regex-paren-left "$"))
(defconst cmake-regex-token-paren-right (concat "^" cmake-regex-paren-right "$"))
;------------------------------------------------------------------------------
@ -127,30 +135,47 @@ set the path with these commands:
(save-excursion
(beginning-of-line)
(let ((point-start (point))
(closing-parens-only (looking-at cmake-regex-closing-parens-line))
(case-fold-search t) ;; case-insensitive
token)
; Search back for the last indented line.
;; Search back for the last indented line.
(cmake-find-last-indented-line)
; Start with the indentation on this line.
;; Start with the indentation on this line.
(setq cur-indent (current-indentation))
; Search forward counting tokens that adjust indentation.
(while (re-search-forward cmake-regex-token point-start t)
(setq token (match-string 0))
(when (or (string-match (concat "^" cmake-regex-paren-left "$") token)
(and (string-match cmake-regex-block-open token)
(looking-at (concat "[ \t]*" cmake-regex-paren-left))))
(setq cur-indent (+ cur-indent cmake-tab-width)))
(when (string-match (concat "^" cmake-regex-paren-right "$") token)
(setq cur-indent (- cur-indent cmake-tab-width)))
)
(goto-char point-start)
;; If next token closes the block, decrease indentation
(when (looking-at cmake-regex-close)
(setq cur-indent (- cur-indent cmake-tab-width))
(if closing-parens-only
(let ((open-parens 0))
(while (re-search-forward cmake-regex-token point-start t)
(setq token (match-string 0))
(cond
((string-match cmake-regex-token-paren-left token)
(setq open-parens (+ open-parens 1)))
((string-match cmake-regex-token-paren-right token)
(setq open-parens (- open-parens 1)))))
;; Don't outdent if last indented line has open parens
(unless (> open-parens 0)
(setq cur-indent (- cur-indent cmake-tab-width))))
;; Skip detailed analysis if last indented line is a 'closing
;; parens only line'
(unless (looking-at cmake-regex-closing-parens-line)
;; Search forward counting tokens that adjust indentation.
(while (re-search-forward cmake-regex-token point-start t)
(setq token (match-string 0))
(when (or (string-match cmake-regex-token-paren-left token)
(and (string-match cmake-regex-block-open token)
(looking-at (concat "[ \t]*" cmake-regex-paren-left))))
(setq cur-indent (+ cur-indent cmake-tab-width)))
(when (string-match cmake-regex-token-paren-right token)
(setq cur-indent (- cur-indent cmake-tab-width)))
))
(goto-char point-start)
;; If next token closes the block, decrease indentation
(when (looking-at cmake-regex-close)
(setq cur-indent (- cur-indent cmake-tab-width))
)
)
)
)
; Indent this line by the amount selected.
;; Indent this line by the amount selected.
(cmake-indent-line-to (max cur-indent 0))
)
)
@ -188,6 +213,61 @@ the indentation. Otherwise it retains the same position on the line"
)
)
;------------------------------------------------------------------------------
;;
;; Navigation / marking by function or macro
;;
(defconst cmake--regex-defun-start
(rx line-start
(zero-or-more space)
(or "function" "macro")
(zero-or-more space)
"("))
(defconst cmake--regex-defun-end
(rx line-start
(zero-or-more space)
"end"
(or "function" "macro")
(zero-or-more space)
"(" (zero-or-more (not-char ")")) ")"))
(defun cmake-beginning-of-defun ()
"Move backward to the beginning of a CMake function or macro.
Return t unless search stops due to beginning of buffer."
(interactive)
(when (not (region-active-p))
(push-mark))
(let ((case-fold-search t))
(when (re-search-backward cmake--regex-defun-start nil 'move)
t)))
(defun cmake-end-of-defun ()
"Move forward to the end of a CMake function or macro.
Return t unless search stops due to end of buffer."
(interactive)
(when (not (region-active-p))
(push-mark))
(let ((case-fold-search t))
(when (re-search-forward cmake--regex-defun-end nil 'move)
(forward-line)
t)))
(defun cmake-mark-defun ()
"Mark the current CMake function or macro.
This puts the mark at the end, and point at the beginning."
(interactive)
(cmake-end-of-defun)
(push-mark nil :nomsg :activate)
(cmake-beginning-of-defun))
;------------------------------------------------------------------------------
;;
@ -208,6 +288,39 @@ the indentation. Otherwise it retains the same position on the line"
;------------------------------------------------------------------------------
(defun cmake--syntax-propertize-until-bracket-close (syntax)
;; This function assumes that a previous search has matched the
;; beginning of a bracket_comment or bracket_argument and that the
;; second capture group has matched the equal signs between the two
;; opening brackets
(let* ((mb (match-beginning 2))
(me (match-end 2))
(cb (format "]%s]" (buffer-substring mb me))))
(save-match-data
(if (search-forward cb end 'move)
(progn
(setq me (match-end 0))
(put-text-property
(1- me)
me
'syntax-table
(string-to-syntax syntax)))
(setq me end)))
(put-text-property
(match-beginning 1)
me
'syntax-multiline
t)))
(defconst cmake--syntax-propertize-function
(syntax-propertize-rules
("\\(#\\)\\[\\(=*\\)\\["
(1
(prog1 "!" (cmake--syntax-propertize-until-bracket-close "!"))))
("\\(\\[\\)\\(=*\\)\\["
(1
(prog1 "|" (cmake--syntax-propertize-until-bracket-close "|"))))))
;; Syntax table for this mode.
(defvar cmake-mode-syntax-table nil
"Syntax table for CMake mode.")
@ -238,7 +351,16 @@ the indentation. Otherwise it retains the same position on the line"
; Setup indentation function.
(set (make-local-variable 'indent-line-function) 'cmake-indent)
; Setup comment syntax.
(set (make-local-variable 'comment-start) "#"))
(set (make-local-variable 'comment-start) "#")
;; Setup syntax propertization
(set (make-local-variable 'syntax-propertize-function) cmake--syntax-propertize-function)
(add-hook 'syntax-propertize-extend-region-functions #'syntax-propertize-multiline nil t))
;; Default cmake-mode key bindings
(define-key cmake-mode-map "\e\C-a" #'cmake-beginning-of-defun)
(define-key cmake-mode-map "\e\C-e" #'cmake-end-of-defun)
(define-key cmake-mode-map "\e\C-h" #'cmake-mark-defun)
; Help mode starts here
@ -258,7 +380,27 @@ optional argument topic will be appended to the argument list."
(save-selected-window
(select-window (display-buffer buffer 'not-this-window))
(cmake-mode)
(read-only-mode 1))
(read-only-mode 1)
(view-mode 1))
)
)
;;;###autoload
(defun cmake-command-run-help (type &optional topic buffer)
"`cmake-command-run' but rendered in `rst-mode'."
(interactive "s")
(let* ((bufname (if buffer buffer (concat "*CMake" type (if topic "-") topic "*")))
(buffer (if (get-buffer bufname) (get-buffer bufname) (generate-new-buffer bufname)))
(command (concat cmake-mode-cmake-executable " " type " " topic))
;; Turn of resizing of mini-windows for shell-command.
(resize-mini-windows nil)
)
(shell-command command buffer)
(save-selected-window
(select-window (display-buffer buffer 'not-this-window))
(rst-mode)
(read-only-mode 1)
(view-mode 1))
)
)
@ -266,7 +408,7 @@ optional argument topic will be appended to the argument list."
(defun cmake-help-list-commands ()
"Prints out a list of the cmake commands."
(interactive)
(cmake-command-run "--help-command-list")
(cmake-command-run-help "--help-command-list")
)
(defvar cmake-commands '() "List of available topics for --help-command.")
@ -292,7 +434,7 @@ and store the result as a list in LISTVAR."
(if (not (symbol-value listvar))
(let ((temp-buffer-name "*CMake Temporary*"))
(save-window-excursion
(cmake-command-run (concat "--help-" listname "-list") nil temp-buffer-name)
(cmake-command-run-help (concat "--help-" listname "-list") nil temp-buffer-name)
(with-current-buffer temp-buffer-name
; FIXME: Ignore first line if it is "cmake version ..." from CMake < 3.0.
(set listvar (split-string (buffer-substring-no-properties (point-min) (point-max)) "\n" t)))))
@ -326,25 +468,25 @@ and store the result as a list in LISTVAR."
(defun cmake-help-command ()
"Prints out the help message for the command the cursor is on."
(interactive)
(cmake-command-run "--help-command" (cmake-help-type "command") "*CMake Help*"))
(cmake-command-run-help "--help-command" (cmake-help-type "command") "*CMake Help*"))
;;;###autoload
(defun cmake-help-module ()
"Prints out the help message for the module the cursor is on."
(interactive)
(cmake-command-run "--help-module" (cmake-help-type "module") "*CMake Help*"))
(cmake-command-run-help "--help-module" (cmake-help-type "module") "*CMake Help*"))
;;;###autoload
(defun cmake-help-variable ()
"Prints out the help message for the variable the cursor is on."
(interactive)
(cmake-command-run "--help-variable" (cmake-help-type "variable") "*CMake Help*"))
(cmake-command-run-help "--help-variable" (cmake-help-type "variable") "*CMake Help*"))
;;;###autoload
(defun cmake-help-property ()
"Prints out the help message for the property the cursor is on."
(interactive)
(cmake-command-run "--help-property" (cmake-help-type "property") "*CMake Help*"))
(cmake-command-run-help "--help-property" (cmake-help-type "property") "*CMake Help*"))
;;;###autoload
(defun cmake-help ()
@ -367,13 +509,13 @@ and store the result as a list in LISTVAR."
(if (string= input "")
(error "No argument given")
(if (member input command-list)
(cmake-command-run "--help-command" input "*CMake Help*")
(cmake-command-run-help "--help-command" input "*CMake Help*")
(if (member input variable-list)
(cmake-command-run "--help-variable" input "*CMake Help*")
(cmake-command-run-help "--help-variable" input "*CMake Help*")
(if (member input module-list)
(cmake-command-run "--help-module" input "*CMake Help*")
(cmake-command-run-help "--help-module" input "*CMake Help*")
(if (member input property-list)
(cmake-command-run "--help-property" input "*CMake Help*")
(cmake-command-run-help "--help-property" input "*CMake Help*")
(error "Not a know help topic.") ; this really should not happen
))))))
)

View File

@ -13,7 +13,7 @@ fi
# $2: language (e.g. C/CXX/Fortran)
# $3: The compiler ID, defaults to GNU.
# Possible values are: GNU, Intel, Clang, SunPro, HP, XL, VisualAge, PGI,
# PathScale, Cray, SCO, MSVC
# PathScale, Cray, SCO, MSVC, LCC
# $4: optional extra arguments to cmake, e.g. "-DCMAKE_SIZEOF_VOID_P=8"
# $5: optional path to cmake binary
AC_DEFUN([CMAKE_FIND_PACKAGE], [

View File

@ -9,7 +9,7 @@
" Former Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com>
" Last Change: @DATE@
"
" Licence: The CMake license applies to this file. See
" License: The CMake license applies to this file. See
" https://cmake.org/licensing
" This implies that distribution with Vim is allowed

View File

@ -3,6 +3,8 @@
use strict;
use warnings;
use POSIX qw(strftime);
use JSON;
use File::Basename;
#my $cmake = "/home/pboettch/devel/upstream/cmake/build/bin/cmake";
my $cmake = "cmake";
@ -96,6 +98,28 @@ close(CMAKE);
# transform all properties in a hash
my %properties = map { $_ => 1 } @properties;
# read in manually written files
my $modules_dir = dirname(__FILE__) . "/modules";
opendir(DIR, $modules_dir) || die "can't opendir $modules_dir: $!";
my @json_files = grep { /\.json$/ && -f "$modules_dir/$_" } readdir(DIR);
closedir DIR;
foreach my $file (@json_files) {
local $/; # Enable 'slurp' mode
open my $fh, "<", $modules_dir."/".$file;
my $json = <$fh>;
close $fh;
my $mod = decode_json($json);
foreach my $var (@{$mod->{variables}}) {
$variables{$var} = 1;
}
while (my ($cmd, $keywords) = each %{$mod->{commands}}) {
$keywords{$cmd} = [ sort @{$keywords} ];
}
}
# version
open(CMAKE, "$cmake --version|");
my $version = 'unknown';

View File

@ -3,9 +3,9 @@
" Author: Andy Cedilnik <andy.cedilnik@kitware.com>
" Maintainer: Dimitri Merejkowsky <d.merej@gmail.com>
" Former Maintainer: Karthik Krishnan <karthik.krishnan@kitware.com>
" Last Change: 2017 Aug 30
" Last Change: 2022 Mar 22
"
" Licence: The CMake license applies to this file. See
" License: The CMake license applies to this file. See
" https://cmake.org/licensing
" This implies that distribution with Vim is allowed
@ -14,9 +14,6 @@ if exists("b:did_indent")
endif
let b:did_indent = 1
let s:keepcpo= &cpo
set cpo&vim
setlocal indentexpr=CMakeGetIndent(v:lnum)
setlocal indentkeys+==ENDIF(,ENDFOREACH(,ENDMACRO(,ELSE(,ELSEIF(,ENDWHILE(
@ -24,6 +21,8 @@ setlocal indentkeys+==ENDIF(,ENDFOREACH(,ENDMACRO(,ELSE(,ELSEIF(,ENDWHILE(
if exists("*CMakeGetIndent")
finish
endif
let s:keepcpo= &cpo
set cpo&vim
fun! CMakeGetIndent(lnum)
let this_line = getline(a:lnum)
@ -54,32 +53,41 @@ fun! CMakeGetIndent(lnum)
let cmake_indent_open_regex = '^\s*' . cmake_regex_identifier .
\ '\s*(' . cmake_regex_arguments .
\ '\(' . cmake_regex_comment . '\)\?$'
let cmake_indent_close_regex = '^' . cmake_regex_arguments .
\ ')\s*' .
\ '\(' . cmake_regex_comment . '\)\?$'
let cmake_indent_begin_regex = '^\s*\(IF\|MACRO\|FOREACH\|ELSE\|ELSEIF\|WHILE\|FUNCTION\)\s*('
let cmake_indent_end_regex = '^\s*\(ENDIF\|ENDFOREACH\|ENDMACRO\|ELSE\|ELSEIF\|ENDWHILE\|ENDFUNCTION\)\s*('
let cmake_closing_parens_line = '^\s*\()\+\)\s*$'
" Add
if previous_line =~? cmake_indent_comment_line " Handle comments
let ind = ind
let cmake_indent_begin_regex = '^\s*\(BLOCK\|IF\|MACRO\|FOREACH\|ELSE\|ELSEIF\|WHILE\|FUNCTION\)\s*('
let cmake_indent_end_regex = '^\s*\(ENDBLOCK\|ENDIF\|ENDFOREACH\|ENDMACRO\|ELSE\|ELSEIF\|ENDWHILE\|ENDFUNCTION\)\s*('
if this_line =~? cmake_closing_parens_line
if previous_line !~? cmake_indent_open_regex
let ind = ind - shiftwidth()
endif
else
if previous_line =~? cmake_indent_begin_regex
let ind = ind + shiftwidth()
" Add
if previous_line =~? cmake_indent_comment_line " Handle comments
let ind = ind
else
if previous_line =~? cmake_indent_begin_regex
let ind = ind + shiftwidth()
endif
if previous_line =~? cmake_indent_open_regex
let ind = ind + shiftwidth()
endif
endif
if previous_line =~? cmake_indent_open_regex
let ind = ind + shiftwidth()
endif
endif
" Subtract
if this_line =~? cmake_indent_end_regex
let ind = ind - shiftwidth()
endif
if previous_line =~? cmake_indent_close_regex
let ind = ind - shiftwidth()
" Subtract
if this_line =~? cmake_indent_end_regex
let ind = ind - shiftwidth()
endif
if previous_line !~? cmake_closing_parens_line
if previous_line =~? cmake_indent_close_regex
let ind = ind - shiftwidth()
endif
endif
endif
return ind

File diff suppressed because it is too large Load Diff

View File

@ -22,6 +22,7 @@ set(CPACK_PACKAGE_NAME "${CMAKE_PROJECT_NAME}")
set(CPACK_PACKAGE_VERSION "${CMake_VERSION}")
set(CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_NAME}")
set(CPACK_SOURCE_PACKAGE_FILE_NAME "cmake-${CMake_VERSION}")
set(CPACK_DMG_SLA_USE_RESOURCE_FILE_LICENSE OFF)
# Installers for 32- vs. 64-bit CMake:
# - Root install directory (displayed to end user at installer-run time)
@ -133,6 +134,9 @@ if(CMake_INSTALL_COMPONENTS)
if(SPHINX_QTHELP)
list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-qthelp)
endif()
if(SPHINX_LATEXPDF)
list(APPEND _CPACK_IFW_COMPONENTS_ALL sphinx-latexpdf)
endif()
if(CMake_BUILD_DEVELOPER_REFERENCE)
if(CMake_BUILD_DEVELOPER_REFERENCE_HTML)
list(APPEND _CPACK_IFW_COMPONENTS_ALL cmake-developer-reference-html)

View File

@ -198,14 +198,6 @@ if(CPACK_GENERATOR MATCHES "IFW")
endif()
if("${CPACK_GENERATOR}" STREQUAL "PackageMaker")
if(CMAKE_PACKAGE_QTGUI)
set(CPACK_PACKAGE_DEFAULT_LOCATION "/Applications")
else()
set(CPACK_PACKAGE_DEFAULT_LOCATION "/usr")
endif()
endif()
if("${CPACK_GENERATOR}" STREQUAL "DragNDrop")
set(CPACK_DMG_BACKGROUND_IMAGE
"@CMake_SOURCE_DIR@/Packaging/CMakeDMGBackground.tif")
@ -256,6 +248,13 @@ if("${CPACK_GENERATOR}" STREQUAL "WIX")
set(CPACK_WIX_LIGHT_EXTRA_FLAGS "-dcl:high")
if(NOT "$ENV{CMAKE_CI_PACKAGE}" STREQUAL "")
# Suppress validation. It does not work without
# an interactive session or an admin account.
# https://github.com/wixtoolset/issues/issues/3968
list(APPEND CPACK_WIX_LIGHT_EXTRA_FLAGS "-sval")
endif()
set(CPACK_WIX_UI_BANNER
"@CMake_SOURCE_DIR@/Utilities/Release/WiX/ui_banner.jpg"
)

View File

@ -1,9 +1,14 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
cmake_minimum_required(VERSION 3.1...3.15 FATAL_ERROR)
cmake_minimum_required(VERSION 3.13...3.23 FATAL_ERROR)
set(CMAKE_USER_MAKE_RULES_OVERRIDE_C ${CMAKE_CURRENT_SOURCE_DIR}/Source/Modules/OverrideC.cmake)
set(CMAKE_USER_MAKE_RULES_OVERRIDE_CXX ${CMAKE_CURRENT_SOURCE_DIR}/Source/Modules/OverrideCXX.cmake)
if(POLICY CMP0129)
cmake_policy(SET CMP0129 NEW) # CMake 3.23
endif()
project(CMake)
unset(CMAKE_USER_MAKE_RULES_OVERRIDE_CXX)
unset(CMAKE_USER_MAKE_RULES_OVERRIDE_C)
@ -12,8 +17,8 @@ unset(CMAKE_USER_MAKE_RULES_OVERRIDE_C)
if(MSVC AND NOT CMAKE_VERSION VERSION_LESS 3.15)
# Filter out MSVC runtime library flags that may have come from
# the cache of an existing build tree or from scripts.
foreach(l C CXX)
foreach(c DEBUG MINSIZEREL RELEASE RELWITHDEBINFO)
foreach(l IN ITEMS C CXX)
foreach(c IN ITEMS DEBUG MINSIZEREL RELEASE RELWITHDEBINFO)
string(REGEX REPLACE "[-/]M[DT]d?( |$)" "" "CMAKE_${l}_FLAGS_${c}" "${CMAKE_${l}_FLAGS_${c}}")
endforeach()
endforeach()
@ -37,7 +42,7 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
if(CMAKE_SYSTEM_NAME STREQUAL "HP-UX")
message(FATAL_ERROR
"CMake no longer compiles on HP-UX. See\n"
" https://gitlab.kitware.com/cmake/cmake/issues/17137\n"
" https://gitlab.kitware.com/cmake/cmake/-/issues/17137\n"
"Use CMake 3.9 or lower instead."
)
endif()
@ -55,17 +60,6 @@ else()
set(USE_LGPL "")
endif()
if("${CMake_SOURCE_DIR}" STREQUAL "${CMAKE_SOURCE_DIR}")
# Disallow architecture-specific try_run. It may not run on the host.
macro(TRY_RUN)
if(CMAKE_TRY_COMPILE_OSX_ARCHITECTURES)
message(FATAL_ERROR "TRY_RUN not allowed with CMAKE_TRY_COMPILE_OSX_ARCHITECTURES=[${CMAKE_TRY_COMPILE_OSX_ARCHITECTURES}]")
else()
_TRY_RUN(${ARGV})
endif()
endmacro()
endif()
# Use most-recent available language dialects with GNU and Clang
if(NOT DEFINED CMAKE_C_STANDARD AND NOT CMake_NO_C_STANDARD)
include(${CMake_SOURCE_DIR}/Source/Checks/cm_c11_thread_local.cmake)
@ -76,7 +70,7 @@ if(NOT DEFINED CMAKE_C_STANDARD AND NOT CMake_NO_C_STANDARD)
endif()
endif()
if(NOT DEFINED CMAKE_CXX_STANDARD AND NOT CMake_NO_CXX_STANDARD)
if (CMAKE_CXX_COMPILER_ID STREQUAL SunPro AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.14)
if(CMAKE_CXX_COMPILER_ID STREQUAL SunPro AND CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.14)
set(CMAKE_CXX_STANDARD 98)
else()
if(NOT CMAKE_VERSION VERSION_LESS 3.8)
@ -108,6 +102,9 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
endif()
endif()
# Inform STL library header wrappers whether to use system versions.
configure_file(Utilities/std/cmSTL.hxx.in Utilities/cmSTL.hxx @ONLY)
# set the internal encoding of CMake to UTF-8
set(KWSYS_ENCODING_DEFAULT_CODEPAGE CP_UTF8)
@ -133,7 +130,7 @@ option(CMake_BUILD_DEVELOPER_REFERENCE
mark_as_advanced(CMake_BUILD_DEVELOPER_REFERENCE)
# option to build using interprocedural optimizations (IPO/LTO)
if (NOT CMAKE_VERSION VERSION_LESS 3.12.2)
if(NOT CMAKE_VERSION VERSION_LESS 3.12.2)
option(CMake_BUILD_LTO "Compile CMake with link-time optimization if supported" OFF)
if(CMake_BUILD_LTO)
include(CheckIPOSupported)
@ -154,8 +151,8 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
# Allow the user to enable/disable all system utility library options by
# defining CMAKE_USE_SYSTEM_LIBRARIES or CMAKE_USE_SYSTEM_LIBRARY_${util}.
set(UTILITIES BZIP2 CURL EXPAT FORM JSONCPP LIBARCHIVE LIBLZMA LIBRHASH LIBUV ZLIB ZSTD)
foreach(util ${UTILITIES})
set(UTILITIES BZIP2 CURL EXPAT FORM JSONCPP LIBARCHIVE LIBLZMA LIBRHASH LIBUV NGHTTP2 ZLIB ZSTD)
foreach(util IN LISTS UTILITIES)
if(NOT DEFINED CMAKE_USE_SYSTEM_LIBRARY_${util}
AND DEFINED CMAKE_USE_SYSTEM_LIBRARIES)
set(CMAKE_USE_SYSTEM_LIBRARY_${util} "${CMAKE_USE_SYSTEM_LIBRARIES}")
@ -192,6 +189,8 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
"${CMAKE_USE_SYSTEM_LIBRARY_ZSTD}" "NOT CMAKE_USE_SYSTEM_LIBARCHIVE" ON)
CMAKE_DEPENDENT_OPTION(CMAKE_USE_SYSTEM_LIBLZMA "Use system-installed liblzma"
"${CMAKE_USE_SYSTEM_LIBRARY_LIBLZMA}" "NOT CMAKE_USE_SYSTEM_LIBARCHIVE" ON)
CMAKE_DEPENDENT_OPTION(CMAKE_USE_SYSTEM_NGHTTP2 "Use system-installed nghttp2"
"${CMAKE_USE_SYSTEM_LIBRARY_NGHTTP2}" "NOT CMAKE_USE_SYSTEM_CURL" ON)
option(CMAKE_USE_SYSTEM_FORM "Use system-installed libform" "${CMAKE_USE_SYSTEM_LIBRARY_FORM}")
option(CMAKE_USE_SYSTEM_JSONCPP "Use system-installed jsoncpp" "${CMAKE_USE_SYSTEM_LIBRARY_JSONCPP}")
option(CMAKE_USE_SYSTEM_LIBRHASH "Use system-installed librhash" "${CMAKE_USE_SYSTEM_LIBRARY_LIBRHASH}")
@ -203,16 +202,14 @@ macro(CMAKE_HANDLE_SYSTEM_LIBRARIES)
mark_as_advanced(CMAKE_USE_SYSTEM_KWIML)
# Mention to the user what system libraries are being used.
foreach(util ${UTILITIES} KWIML)
foreach(util IN LISTS UTILITIES ITEMS KWIML)
if(CMAKE_USE_SYSTEM_${util})
message(STATUS "Using system-installed ${util}")
endif()
endforeach()
# Inform utility library header wrappers whether to use system versions.
configure_file(${CMake_SOURCE_DIR}/Utilities/cmThirdParty.h.in
${CMake_BINARY_DIR}/Utilities/cmThirdParty.h
@ONLY)
configure_file(Utilities/cmThirdParty.h.in Utilities/cmThirdParty.h @ONLY)
endmacro()
@ -223,7 +220,7 @@ endmacro()
macro(CMAKE_SETUP_TESTING)
if(BUILD_TESTING)
set(CMAKE_TEST_SYSTEM_LIBRARIES 0)
foreach(util CURL EXPAT ZLIB)
foreach(util IN ITEMS CURL EXPAT ZLIB)
if(CMAKE_USE_SYSTEM_${util})
set(CMAKE_TEST_SYSTEM_LIBRARIES 1)
endif()
@ -238,7 +235,7 @@ macro(CMAKE_SETUP_TESTING)
set(CMAKE_CTEST_COMMAND "${CMake_TEST_EXTERNAL_CMAKE}/ctest")
set(CMAKE_CMAKE_COMMAND "${CMake_TEST_EXTERNAL_CMAKE}/cmake")
set(CMAKE_CPACK_COMMAND "${CMake_TEST_EXTERNAL_CMAKE}/cpack")
foreach(exe cmake ctest cpack)
foreach(exe IN ITEMS cmake ctest cpack)
add_executable(${exe} IMPORTED)
set_property(TARGET ${exe} PROPERTY IMPORTED_LOCATION ${CMake_TEST_EXTERNAL_CMAKE}/${exe})
endforeach()
@ -250,21 +247,14 @@ macro(CMAKE_SETUP_TESTING)
endif()
# configure some files for testing
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/Templates/CTestScript.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/CTestScript.cmake"
@ONLY)
configure_file(${CMake_SOURCE_DIR}/Tests/.NoDartCoverage
${CMake_BINARY_DIR}/Tests/.NoDartCoverage)
configure_file(${CMake_SOURCE_DIR}/Tests/.NoDartCoverage
${CMake_BINARY_DIR}/Modules/.NoDartCoverage)
configure_file(${CMake_SOURCE_DIR}/CTestCustom.cmake.in
${CMake_BINARY_DIR}/CTestCustom.cmake @ONLY)
configure_file(Templates/CTestScript.cmake.in CTestScript.cmake @ONLY)
configure_file(Tests/.NoDartCoverage Tests/.NoDartCoverage)
configure_file(Tests/.NoDartCoverage Modules/.NoDartCoverage)
configure_file(CTestCustom.cmake.in CTestCustom.cmake @ONLY)
if(BUILD_TESTING AND DART_ROOT)
configure_file(${CMake_SOURCE_DIR}/CMakeLogo.gif
${CMake_BINARY_DIR}/Testing/HTML/TestingResults/Icons/Logo.gif COPYONLY)
configure_file(CMakeLogo.gif Testing/HTML/TestingResults/Icons/Logo.gif COPYONLY)
endif()
mark_as_advanced(DART_ROOT)
mark_as_advanced(CURL_TESTING)
endmacro()
@ -328,310 +318,6 @@ macro(CMAKE_SET_TARGET_FOLDER tgt folder)
endif()
endmacro()
#-----------------------------------------------------------------------
# a macro to build the utilities used by CMake
# Simply to improve readability of the main script.
#-----------------------------------------------------------------------
macro (CMAKE_BUILD_UTILITIES)
find_package(Threads)
#---------------------------------------------------------------------
# Create the kwsys library for CMake.
set(KWSYS_NAMESPACE cmsys)
set(KWSYS_USE_SystemTools 1)
set(KWSYS_USE_Directory 1)
set(KWSYS_USE_RegularExpression 1)
set(KWSYS_USE_Base64 1)
set(KWSYS_USE_MD5 1)
set(KWSYS_USE_Process 1)
set(KWSYS_USE_CommandLineArguments 1)
set(KWSYS_USE_ConsoleBuf 1)
set(KWSYS_HEADER_ROOT ${CMake_BINARY_DIR}/Source)
set(KWSYS_INSTALL_DOC_DIR "${CMAKE_DOC_DIR}")
if(CMake_NO_CXX_STANDARD)
set(KWSYS_CXX_STANDARD "")
endif()
add_subdirectory(Source/kwsys)
set(kwsys_folder "Utilities/KWSys")
CMAKE_SET_TARGET_FOLDER(${KWSYS_NAMESPACE} "${kwsys_folder}")
CMAKE_SET_TARGET_FOLDER(${KWSYS_NAMESPACE}_c "${kwsys_folder}")
if(BUILD_TESTING)
CMAKE_SET_TARGET_FOLDER(${KWSYS_NAMESPACE}TestDynload "${kwsys_folder}")
CMAKE_SET_TARGET_FOLDER(${KWSYS_NAMESPACE}TestProcess "${kwsys_folder}")
CMAKE_SET_TARGET_FOLDER(${KWSYS_NAMESPACE}TestsC "${kwsys_folder}")
CMAKE_SET_TARGET_FOLDER(${KWSYS_NAMESPACE}TestsCxx "${kwsys_folder}")
CMAKE_SET_TARGET_FOLDER(${KWSYS_NAMESPACE}TestSharedForward "${kwsys_folder}")
endif()
#---------------------------------------------------------------------
# Setup third-party libraries.
# Everything in the tree should be able to include files from the
# Utilities directory.
if (CMAKE_SYSTEM_NAME STREQUAL "AIX" AND CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
# using -isystem option generate error "template with C linkage"
include_directories("${CMake_SOURCE_DIR}/Utilities/std")
else()
include_directories(SYSTEM "${CMake_SOURCE_DIR}/Utilities/std")
endif()
include_directories(
${CMake_BINARY_DIR}/Utilities
${CMake_SOURCE_DIR}/Utilities
)
#---------------------------------------------------------------------
# Build CMake std library for CMake and CTest.
set(CMAKE_STD_LIBRARY cmstd)
add_subdirectory(Utilities/std)
CMAKE_SET_TARGET_FOLDER(cmstd "Utilities/std")
# check for the use of system libraries versus builtin ones
# (a macro defined in this file)
CMAKE_HANDLE_SYSTEM_LIBRARIES()
if(CMAKE_USE_SYSTEM_KWIML)
find_package(KWIML 1.0)
if(NOT KWIML_FOUND)
message(FATAL_ERROR "CMAKE_USE_SYSTEM_KWIML is ON but KWIML is not found!")
endif()
set(CMake_KWIML_LIBRARIES kwiml::kwiml)
else()
set(CMake_KWIML_LIBRARIES "")
if(BUILD_TESTING)
set(KWIML_TEST_ENABLE 1)
endif()
add_subdirectory(Utilities/KWIML)
endif()
if(CMAKE_USE_SYSTEM_LIBRHASH)
find_package(LibRHash)
if(NOT LibRHash_FOUND)
message(FATAL_ERROR
"CMAKE_USE_SYSTEM_LIBRHASH is ON but LibRHash is not found!")
endif()
set(CMAKE_LIBRHASH_LIBRARIES LibRHash::LibRHash)
else()
set(CMAKE_LIBRHASH_LIBRARIES cmlibrhash)
add_subdirectory(Utilities/cmlibrhash)
CMAKE_SET_TARGET_FOLDER(cmlibrhash "Utilities/3rdParty")
endif()
#---------------------------------------------------------------------
# Build zlib library for Curl, CMake, and CTest.
set(CMAKE_ZLIB_HEADER "cm_zlib.h")
if(CMAKE_USE_SYSTEM_ZLIB)
find_package(ZLIB)
if(NOT ZLIB_FOUND)
message(FATAL_ERROR
"CMAKE_USE_SYSTEM_ZLIB is ON but a zlib is not found!")
endif()
set(CMAKE_ZLIB_INCLUDES ${ZLIB_INCLUDE_DIR})
set(CMAKE_ZLIB_LIBRARIES ${ZLIB_LIBRARIES})
else()
set(CMAKE_ZLIB_INCLUDES ${CMake_SOURCE_DIR}/Utilities)
set(CMAKE_ZLIB_LIBRARIES cmzlib)
add_subdirectory(Utilities/cmzlib)
CMAKE_SET_TARGET_FOLDER(cmzlib "Utilities/3rdParty")
endif()
#---------------------------------------------------------------------
# Build Curl library for CTest.
if(CMAKE_USE_SYSTEM_CURL)
find_package(CURL)
if(NOT CURL_FOUND)
message(FATAL_ERROR
"CMAKE_USE_SYSTEM_CURL is ON but a curl is not found!")
endif()
set(CMAKE_CURL_INCLUDES ${CURL_INCLUDE_DIRS})
set(CMAKE_CURL_LIBRARIES ${CURL_LIBRARIES})
else()
set(CURL_SPECIAL_ZLIB_H ${CMAKE_ZLIB_HEADER})
set(CURL_SPECIAL_LIBZ_INCLUDES ${CMAKE_ZLIB_INCLUDES})
set(CURL_SPECIAL_LIBZ ${CMAKE_ZLIB_LIBRARIES})
set(CMAKE_CURL_INCLUDES)
set(CMAKE_CURL_LIBRARIES cmcurl)
if(CMAKE_TESTS_CDASH_SERVER)
set(CMAKE_CURL_TEST_URL "${CMAKE_TESTS_CDASH_SERVER}/user.php")
endif()
set(_CMAKE_USE_OPENSSL_DEFAULT OFF)
if(NOT DEFINED CMAKE_USE_OPENSSL AND NOT WIN32 AND NOT APPLE
AND CMAKE_SYSTEM_NAME MATCHES "(Linux|FreeBSD)")
set(_CMAKE_USE_OPENSSL_DEFAULT ON)
endif()
option(CMAKE_USE_OPENSSL "Use OpenSSL." ${_CMAKE_USE_OPENSSL_DEFAULT})
mark_as_advanced(CMAKE_USE_OPENSSL)
if(CMAKE_USE_OPENSSL)
set(CURL_CA_BUNDLE "" CACHE FILEPATH "Path to SSL CA Certificate Bundle")
set(CURL_CA_PATH "" CACHE PATH "Path to SSL CA Certificate Directory")
mark_as_advanced(CURL_CA_BUNDLE CURL_CA_PATH)
endif()
add_subdirectory(Utilities/cmcurl)
CMAKE_SET_TARGET_FOLDER(cmcurl "Utilities/3rdParty")
CMAKE_SET_TARGET_FOLDER(LIBCURL "Utilities/3rdParty")
endif()
#---------------------------------------------------------------------
# Build expat library for CMake, CTest, and libarchive.
if(CMAKE_USE_SYSTEM_EXPAT)
find_package(EXPAT)
if(NOT EXPAT_FOUND)
message(FATAL_ERROR
"CMAKE_USE_SYSTEM_EXPAT is ON but a expat is not found!")
endif()
set(CMAKE_EXPAT_INCLUDES ${EXPAT_INCLUDE_DIRS})
set(CMAKE_EXPAT_LIBRARIES ${EXPAT_LIBRARIES})
else()
set(CMAKE_EXPAT_INCLUDES)
set(CMAKE_EXPAT_LIBRARIES cmexpat)
add_subdirectory(Utilities/cmexpat)
CMAKE_SET_TARGET_FOLDER(cmexpat "Utilities/3rdParty")
endif()
#---------------------------------------------------------------------
# Build or use system libbz2 for libarchive.
if(NOT CMAKE_USE_SYSTEM_LIBARCHIVE)
if(CMAKE_USE_SYSTEM_BZIP2)
find_package(BZip2)
else()
set(BZIP2_INCLUDE_DIR
"${CMAKE_CURRENT_SOURCE_DIR}/Utilities/cmbzip2")
set(BZIP2_LIBRARIES cmbzip2)
add_subdirectory(Utilities/cmbzip2)
CMAKE_SET_TARGET_FOLDER(cmbzip2 "Utilities/3rdParty")
endif()
endif()
#---------------------------------------------------------------------
# Build or use system zstd for libarchive.
if(NOT CMAKE_USE_SYSTEM_LIBARCHIVE)
if(NOT CMAKE_USE_SYSTEM_ZSTD)
set(ZSTD_INCLUDE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/Utilities/cmzstd")
set(ZSTD_LIBRARY cmzstd)
add_subdirectory(Utilities/cmzstd)
CMAKE_SET_TARGET_FOLDER(cmzstd "Utilities/3rdParty")
endif()
endif()
#---------------------------------------------------------------------
# Build or use system liblzma for libarchive.
if(NOT CMAKE_USE_SYSTEM_LIBARCHIVE)
if(CMAKE_USE_SYSTEM_LIBLZMA)
find_package(LibLZMA)
if(NOT LIBLZMA_FOUND)
message(FATAL_ERROR "CMAKE_USE_SYSTEM_LIBLZMA is ON but LibLZMA is not found!")
endif()
else()
add_subdirectory(Utilities/cmliblzma)
CMAKE_SET_TARGET_FOLDER(cmliblzma "Utilities/3rdParty")
set(LIBLZMA_HAS_AUTO_DECODER 1)
set(LIBLZMA_HAS_EASY_ENCODER 1)
set(LIBLZMA_HAS_LZMA_PRESET 1)
set(LIBLZMA_INCLUDE_DIR
"${CMAKE_CURRENT_SOURCE_DIR}/Utilities/cmliblzma/liblzma/api")
set(LIBLZMA_LIBRARY cmliblzma)
endif()
endif()
#---------------------------------------------------------------------
# Build or use system libarchive for CMake and CTest.
if(CMAKE_USE_SYSTEM_LIBARCHIVE)
find_package(LibArchive 3.3.3)
if(NOT LibArchive_FOUND)
message(FATAL_ERROR "CMAKE_USE_SYSTEM_LIBARCHIVE is ON but LibArchive is not found!")
endif()
set(CMAKE_TAR_INCLUDES ${LibArchive_INCLUDE_DIRS})
set(CMAKE_TAR_LIBRARIES ${LibArchive_LIBRARIES})
else()
set(EXPAT_INCLUDE_DIR ${CMAKE_EXPAT_INCLUDES})
set(EXPAT_LIBRARY ${CMAKE_EXPAT_LIBRARIES})
set(ZLIB_INCLUDE_DIR ${CMAKE_ZLIB_INCLUDES})
set(ZLIB_LIBRARY ${CMAKE_ZLIB_LIBRARIES})
add_definitions(-DLIBARCHIVE_STATIC)
set(ENABLE_NETTLE OFF CACHE INTERNAL "Enable use of Nettle")
set(ENABLE_OPENSSL ${CMAKE_USE_OPENSSL} CACHE INTERNAL "Enable use of OpenSSL")
set(ENABLE_LZMA ON CACHE INTERNAL "Enable the use of the system LZMA library if found")
set(ENABLE_LZ4 OFF CACHE INTERNAL "Enable the use of the system LZ4 library if found")
set(ENABLE_LZO OFF CACHE INTERNAL "Enable the use of the system LZO library if found")
set(ENABLE_ZLIB ON CACHE INTERNAL "Enable the use of the system ZLIB library if found")
set(ENABLE_BZip2 ON CACHE INTERNAL "Enable the use of the system BZip2 library if found")
set(ENABLE_LIBXML2 OFF CACHE INTERNAL "Enable the use of the system libxml2 library if found")
set(ENABLE_EXPAT ON CACHE INTERNAL "Enable the use of the system EXPAT library if found")
set(ENABLE_PCREPOSIX OFF CACHE INTERNAL "Enable the use of the system PCREPOSIX library if found")
set(ENABLE_LibGCC OFF CACHE INTERNAL "Enable the use of the system LibGCC library if found")
set(ENABLE_XATTR OFF CACHE INTERNAL "Enable extended attribute support")
set(ENABLE_ACL OFF CACHE INTERNAL "Enable ACL support")
set(ENABLE_ICONV OFF CACHE INTERNAL "Enable iconv support")
set(ENABLE_CNG OFF CACHE INTERNAL "Enable the use of CNG(Crypto Next Generation)")
add_subdirectory(Utilities/cmlibarchive)
CMAKE_SET_TARGET_FOLDER(cmlibarchive "Utilities/3rdParty")
set(CMAKE_TAR_LIBRARIES cmlibarchive ${BZIP2_LIBRARIES})
endif()
#---------------------------------------------------------------------
# Build jsoncpp library.
if(CMAKE_USE_SYSTEM_JSONCPP)
find_package(JsonCpp 1.4.1)
if(NOT JsonCpp_FOUND)
message(FATAL_ERROR
"CMAKE_USE_SYSTEM_JSONCPP is ON but a JsonCpp is not found!")
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
set_property(TARGET JsonCpp::JsonCpp APPEND PROPERTY
INTERFACE_COMPILE_OPTIONS -Wno-deprecated-declarations)
endif()
set(CMAKE_JSONCPP_LIBRARIES JsonCpp::JsonCpp)
else()
set(CMAKE_JSONCPP_LIBRARIES cmjsoncpp)
add_subdirectory(Utilities/cmjsoncpp)
CMAKE_SET_TARGET_FOLDER(cmjsoncpp "Utilities/3rdParty")
endif()
#---------------------------------------------------------------------
# Build libuv library.
if(CMAKE_USE_SYSTEM_LIBUV)
find_package(LibUV 1.10.0)
if(NOT LIBUV_FOUND)
message(FATAL_ERROR
"CMAKE_USE_SYSTEM_LIBUV is ON but a libuv is not found!")
endif()
set(CMAKE_LIBUV_LIBRARIES LibUV::LibUV)
else()
set(CMAKE_LIBUV_LIBRARIES cmlibuv)
add_subdirectory(Utilities/cmlibuv)
CMAKE_SET_TARGET_FOLDER(cmlibuv "Utilities/3rdParty")
endif()
#---------------------------------------------------------------------
# Use curses?
if (UNIX)
if(NOT DEFINED BUILD_CursesDialog)
include(${CMake_SOURCE_DIR}/Source/Checks/Curses.cmake)
option(BUILD_CursesDialog "Build the CMake Curses Dialog ccmake" "${CMakeCheckCurses_COMPILED}")
endif()
else ()
set(BUILD_CursesDialog 0)
endif ()
if(BUILD_CursesDialog)
set(CURSES_NEED_NCURSES TRUE)
find_package(Curses)
if(NOT CURSES_FOUND)
message(WARNING
"'ccmake' will not be built because Curses was not found.\n"
"Turn off BUILD_CursesDialog to suppress this message."
)
set(BUILD_CursesDialog 0)
endif()
endif()
if(BUILD_CursesDialog)
if(NOT CMAKE_USE_SYSTEM_FORM)
add_subdirectory(Source/CursesDialog/form)
elseif(NOT CURSES_FORM_LIBRARY)
message( FATAL_ERROR "CMAKE_USE_SYSTEM_FORM in ON but CURSES_FORM_LIBRARY is not set!" )
endif()
endif()
endmacro ()
#-----------------------------------------------------------------------
if(NOT CMake_TEST_EXTERNAL_CMAKE)
if(CMAKE_CXX_PLATFORM_ID MATCHES "OpenBSD")
@ -658,7 +344,7 @@ include(Source/CMakeVersion.cmake)
# Include the standard Dart testing module
enable_testing()
include (${CMAKE_ROOT}/Modules/Dart.cmake)
include(${CMAKE_ROOT}/Modules/Dart.cmake)
# Set up test-time configuration.
set_directory_properties(PROPERTIES
@ -671,10 +357,6 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
set(LIBRARY_OUTPUT_PATH "" CACHE INTERNAL
"Where to put the libraries for CMake")
# The CMake executables usually do not need any rpath to run in the build or
# install tree.
set(CMAKE_SKIP_RPATH ON CACHE INTERNAL "CMake does not need RPATHs.")
# Load install destinations.
include(Source/CMakeInstallDestinations.cmake)
@ -682,10 +364,15 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
include(${CMake_SOURCE_DIR}/Tests/CMakeInstall.cmake)
endif()
# no clue why we are testing for this here
include(CheckSymbolExists)
CHECK_SYMBOL_EXISTS(unsetenv "stdlib.h" HAVE_UNSETENV)
CHECK_SYMBOL_EXISTS(environ "stdlib.h" HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
# Checks for cmSystemTools.
if(WIN32)
set(HAVE_UNSETENV 0)
set(HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE 1)
else()
include(CheckSymbolExists)
CHECK_SYMBOL_EXISTS(unsetenv "stdlib.h" HAVE_UNSETENV)
CHECK_SYMBOL_EXISTS(environ "stdlib.h" HAVE_ENVIRON_NOT_REQUIRE_PROTOTYPE)
endif()
endif()
# CMAKE_TESTS_CDASH_SERVER: CDash server used by CMake/Tests.
@ -711,21 +398,9 @@ if(CMake_TEST_EXTERNAL_CMAKE)
endif()
if(NOT CMake_TEST_EXTERNAL_CMAKE)
# build the utilities (a macro defined in this file)
CMAKE_BUILD_UTILITIES()
# On NetBSD ncurses is required, since curses doesn't have the wsyncup()
# function. ncurses is installed via pkgsrc, so the library is in /usr/pkg/lib,
# which isn't in the default linker search path. So without RPATH ccmake
# doesn't run and the build doesn't succeed since ccmake is executed for
# generating the documentation.
if(BUILD_CursesDialog)
get_filename_component(_CURSES_DIR "${CURSES_LIBRARY}" PATH)
set(CURSES_NEED_RPATH FALSE)
if(NOT "${_CURSES_DIR}" STREQUAL "/lib" AND NOT "${_CURSES_DIR}" STREQUAL "/usr/lib" AND NOT "${_CURSES_DIR}" STREQUAL "/lib64" AND NOT "${_CURSES_DIR}" STREQUAL "/usr/lib64")
set(CURSES_NEED_RPATH TRUE)
endif()
endif()
find_package(Threads)
# build the utilities
include(CMakeBuildUtilities)
if(BUILD_QtDialog)
if(APPLE)
@ -734,43 +409,26 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
set(CMAKE_BUNDLE_LOCATION "${CMAKE_INSTALL_PREFIX}")
# make sure CMAKE_INSTALL_PREFIX ends in /
if(NOT CMAKE_INSTALL_PREFIX MATCHES "/$")
set(CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}/")
string(APPEND CMAKE_INSTALL_PREFIX "/")
endif()
set(CMAKE_INSTALL_PREFIX
"${CMAKE_INSTALL_PREFIX}CMake.app/Contents")
endif()
set(QT_NEED_RPATH FALSE)
if(NOT "${QT_LIBRARY_DIR}" STREQUAL "/lib" AND NOT "${QT_LIBRARY_DIR}" STREQUAL "/usr/lib" AND NOT "${QT_LIBRARY_DIR}" STREQUAL "/lib64" AND NOT "${QT_LIBRARY_DIR}" STREQUAL "/usr/lib64")
set(QT_NEED_RPATH TRUE)
string(APPEND CMAKE_INSTALL_PREFIX "CMake.app/Contents")
endif()
endif()
# The same might be true on other systems for other libraries.
# Then only enable RPATH if we have are building at least with cmake 2.4,
# since this one has much better RPATH features than cmake 2.2.
# The executables are then built with the RPATH for the libraries outside
# the build tree, which is both the build and the install RPATH.
if (UNIX)
if( CMAKE_USE_SYSTEM_CURL OR CMAKE_USE_SYSTEM_ZLIB
OR CMAKE_USE_SYSTEM_EXPAT OR CURSES_NEED_RPATH OR QT_NEED_RPATH)
set(CMAKE_SKIP_RPATH OFF CACHE INTERNAL "CMake built with RPATH.")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
endif()
endif ()
if(UNIX)
# Install executables with the RPATH set for libraries outside the build tree.
# This is also suitable for binaries in the build tree. Avoid re-link on install.
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH ON CACHE BOOL "Install with RPATH set to find custom-built libraries.")
set(CMAKE_BUILD_WITH_INSTALL_RPATH ON CACHE BOOL "Build with RPATH set to match install-tree RPATH.")
mark_as_advanced(CMAKE_INSTALL_RPATH_USE_LINK_PATH CMAKE_BUILD_WITH_INSTALL_RPATH)
endif()
# add the uninstall support
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
@ONLY)
configure_file(cmake_uninstall.cmake.in cmake_uninstall.cmake @ONLY)
add_custom_target(uninstall
"${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake")
include (CMakeCPack.cmake)
include(CMakeCPack.cmake)
endif()
@ -779,8 +437,13 @@ CMAKE_SETUP_TESTING()
if(NOT CMake_TEST_EXTERNAL_CMAKE)
if(NOT CMake_VERSION_IS_RELEASE)
if(CMAKE_C_COMPILER_ID STREQUAL "GNU" AND
NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS 4.2)
if((CMAKE_C_COMPILER_ID STREQUAL "GNU" AND
NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS 4.2) OR
(CMAKE_C_COMPILER_ID STREQUAL "Clang" AND
NOT "${CMAKE_C_COMPILER_VERSION}" VERSION_LESS 3.0 AND
NOT "x${CMAKE_C_SIMULATE_ID}" STREQUAL "xMSVC") OR
CMAKE_C_COMPILER_ID STREQUAL "AppleClang" OR
CMAKE_C_COMPILER_ID STREQUAL "LCC")
set(C_FLAGS_LIST -Wcast-align -Werror-implicit-function-declaration -Wchar-subscripts
-Wall -W -Wpointer-arith -Wwrite-strings -Wformat-security
-Wmissing-format-attribute -fno-common -Wundef
@ -789,10 +452,10 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
-Wshadow -Wpointer-arith -Wformat-security -Wundef
)
foreach(FLAG_LANG C CXX)
foreach(FLAG ${${FLAG_LANG}_FLAGS_LIST})
foreach(FLAG_LANG IN ITEMS C CXX)
foreach(FLAG IN LISTS ${FLAG_LANG}_FLAGS_LIST)
if(NOT " ${CMAKE_${FLAG_LANG}_FLAGS} " MATCHES " ${FLAG} ")
set(CMAKE_${FLAG_LANG}_FLAGS "${CMAKE_${FLAG_LANG}_FLAGS} ${FLAG}")
string(APPEND CMAKE_${FLAG_LANG}_FLAGS " ${FLAG}")
endif()
endforeach()
endforeach()
@ -812,9 +475,6 @@ add_subdirectory(Tests)
if(NOT CMake_TEST_EXTERNAL_CMAKE)
if(BUILD_TESTING)
CMAKE_SET_TARGET_FOLDER(CMakeLibTests "Tests")
IF(TARGET CMakeServerLibTests)
CMAKE_SET_TARGET_FOLDER(CMakeServerLibTests "Tests")
ENDIF()
endif()
if(TARGET documentation)
CMAKE_SET_TARGET_FOLDER(documentation "Documentation")
@ -823,7 +483,8 @@ endif()
if(BUILD_TESTING)
add_test(SystemInformationNew "${CMAKE_CMAKE_COMMAND}"
--system-information -G "${CMAKE_GENERATOR}" )
--system-information -G "${CMAKE_GENERATOR}"
)
endif()
if(NOT CMake_TEST_EXTERNAL_CMAKE)
@ -841,6 +502,10 @@ if(NOT CMake_TEST_EXTERNAL_CMAKE)
PATTERN "*.sh*" PERMISSIONS OWNER_READ OWNER_EXECUTE OWNER_WRITE
GROUP_READ GROUP_EXECUTE
WORLD_READ WORLD_EXECUTE
REGEX "/(ExportImportList|cpp)$"
PERMISSIONS OWNER_READ OWNER_EXECUTE OWNER_WRITE
GROUP_READ GROUP_EXECUTE
WORLD_READ WORLD_EXECUTE
REGEX "Help/(dev|guide)($|/)" EXCLUDE
)

View File

@ -11,11 +11,11 @@ Community
CMake is maintained and supported by `Kitware`_ and developed in
collaboration with a productive community of contributors.
Please subscribe and post to the `CMake Developers List`_ to raise
Please post to the ``Development`` category of the `CMake Forum`_ to raise
discussion of development topics.
.. _`Kitware`: http://www.kitware.com/cmake
.. _`CMake Developers List`: https://cmake.org/mailman/listinfo/cmake-developers
.. _`CMake Forum`: https://discourse.cmake.org
Patches
=======
@ -38,7 +38,7 @@ To contribute patches:
#. Push the topic branch to a personal repository fork on GitLab.
#. Create a GitLab Merge Request targeting the upstream ``master`` branch
(even if the change is intended for merge to the ``release`` branch).
Check the box labelled "Allow commits from members who can merge to the
Check the box labeled "Allow commits from members who can merge to the
target branch". This will allow maintainers to make minor edits on your
behalf.

View File

@ -1,10 +1,14 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
# If changing this file, also update Utilities/Sphinx/CTestConfig.cmake
set(CTEST_PROJECT_NAME "CMake")
set(CTEST_NIGHTLY_START_TIME "1:00:00 UTC")
set(CTEST_DROP_METHOD "http")
if(NOT CTEST_DROP_METHOD STREQUAL "https")
set(CTEST_DROP_METHOD "http")
endif()
set(CTEST_DROP_SITE "open.cdash.org")
set(CTEST_DROP_LOCATION "/submit.php?project=CMake")
set(CTEST_DROP_SITE_CDASH TRUE)

View File

@ -7,10 +7,12 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
"warning LNK4221"
"warning LNK4204" # Occurs by race condition with objects in small libs
"variable .var_args[2]*. is used before its value is set"
"warning: variable .__d[01]. was set but never used" # FD_ZERO on NVHPC
"jobserver unavailable"
"warning: \\(Long double usage is reported only once for each file"
"warning: To disable this warning use"
"could not be inlined"
"libcmexpat.*has no symbols"
"libcmcurl.*has no symbols"
"not sorted slower link editing will result"
"stl_deque.h:479"
@ -64,6 +66,7 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
"ld: warning .*/libgcc.a archive's cputype"
"ld: warning: ignoring file .*/libgcc.a, file was built for archive which is not the architecture being linked"
"ld: warning: in .*/libgcc.a, file is not of required architecture"
"ld: warning: symbol .(deflate|inflate)_copyright. has differing sizes" # system libz and QtCore disagree
"warning.*This version of Mac OS X is unsupported"
"clang.*: warning: argument unused during compilation: .-g"
"note: in expansion of macro" # diagnostic context note
@ -71,7 +74,9 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
"cm(StringCommand|CTestTestHandler)\\.cxx.*warning.*rand.*may return deterministic values"
"cm(StringCommand|CTestTestHandler)\\.cxx.*warning.*rand.*isn.*t random" # we do not do crypto
"cm(StringCommand|CTestTestHandler)\\.cxx.*warning.*srand.*seed choices are.*poor" # we do not do crypto
"cmFindPackageCommand.cxx.*: warning #177-D: parameter .* was declared but never referenced"
"IPA warning: function.*multiply defined in"
"LICENSE WARNING" # PGI license expiry. Not useful in nightly testing.
# Ignore compiler summary warning, assuming prior text has matched some
# other warning expression:
@ -79,25 +84,27 @@ list(APPEND CTEST_CUSTOM_WARNING_EXCEPTION
"compilation completed with warnings" # PGI
"[0-9]+ Warning\\(s\\) detected" # SunPro
# scanbuild exceptions
"char_traits.h:.*: warning: Null pointer argument in call to string length function"
"stl_construct.h:.*: warning: Forming reference to null pointer"
".*stl_uninitialized.h:75:19: warning: Forming reference to null pointer.*"
".*stl_vector.h:.*: warning: Returning null reference.*"
"warning: Value stored to 'yymsg' is never read"
"warning: Value stored to 'yytoken' is never read"
"index_encoder.c.241.2. warning: Value stored to .out_start. is never read"
"index.c.*warning: Access to field.*results in a dereference of a null pointer.*loaded from variable.*"
"cmCommandArgumentLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
"cmDependsJavaLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
"cmExprLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
"cmListFileLexer.c:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
"cmFortranLexer.cxx:[0-9]+:[0-9]+: warning: Call to 'realloc' has an allocation size of 0 bytes"
"testProcess.*warning: Dereference of null pointer .loaded from variable .invalidAddress.."
# Ignore false positive on `cm::optional` usage from GCC
"cmGlobalNinjaGenerator.cxx:[0-9]*:[0-9]*: warning: '.*cm::optional<CxxModuleMapFormat>::_mem\\)\\)' may be used uninitialized \\[-Wmaybe-uninitialized\\]"
"cmGlobalNinjaGenerator.cxx:[0-9]*:[0-9]*: note: '.*cm::optional<CxxModuleMapFormat>::_mem\\)\\)' was declared here"
"cmGlobalNinjaGenerator.cxx:[0-9]*:[0-9]*: warning: '\\*\\(\\(void\\*\\)& modmap_fmt \\+4\\)' may be used uninitialized in this function \\[-Wmaybe-uninitialized\\]"
# clang-analyzer exceptions
"cmListFileLexer.c:[0-9]+:[0-9]+: warning: Array subscript is undefined"
"jsoncpp/src/.*:[0-9]+:[0-9]+: warning: Value stored to .* is never read"
"liblzma/common/index_encoder.c:[0-9]+:[0-9]+: warning: Value stored to '[^']+' during its initialization is never read"
"liblzma/liblzma/common/index.c:[0-9]+:[0-9]+: warning: Access to field '[^']+' results in a dereference of a null pointer"
"liblzma/simple/x86.c:[0-9]+:[0-9]+: warning: The result of the '<<' expression is undefined"
"liblzma/common/index_encoder.c:[0-9]+:[0-9]+: warning: Value stored to .* during its initialization is never read"
"librhash/librhash/.*:[0-9]+:[0-9]+: warning: The left operand of '[^']+' is a garbage value"
"libuv/src/.*:[0-9]+:[0-9]+: warning: 1st function call argument is an uninitialized value"
"libuv/src/.*:[0-9]+:[0-9]+: warning: Dereference of null pointer"
"libuv/src/.*:[0-9]+:[0-9]+: warning: The left operand of '==' is a garbage value"
"libuv/src/.*:[0-9]+:[0-9]+: warning: The left operand of '[^']+' is a garbage value"
"nghttp2/lib/.*:[0-9]+:[0-9]+: warning: Access to field '[^']+' results in a dereference of a null pointer"
"nghttp2/lib/.*:[0-9]+:[0-9]+: warning: Dereference of null pointer"
"nghttp2/lib/.*:[0-9]+:[0-9]+: warning: Value stored to '[^']+' is never read"
"zstd/lib/.*:[0-9]+:[0-9]+: warning: Assigned value is garbage or undefined"
"zstd/lib/.*:[0-9]+:[0-9]+: warning: Dereference of null pointer"
"zstd/lib/.*:[0-9]+:[0-9]+: warning: The right operand of .* is a garbage value due to array index out of bounds"
)
if(NOT "@CMAKE_GENERATOR@" MATCHES "Xcode")

View File

@ -18,12 +18,18 @@ endif()
# not hurt other versions, and this will work into the
# future
if(MSVC OR _INTEL_WINDOWS OR _CLANG_MSVC_WINDOWS)
add_definitions(-D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE)
add_compile_definitions(_CRT_SECURE_NO_DEPRECATE _CRT_NONSTDC_NO_DEPRECATE)
else()
endif()
if(MSVC)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -stack:10000000")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${CMAKE_CXX_LINKER_WRAPPER_FLAG}-stack:10000000")
endif()
# MSVC 14.28 enables C5105, but the Windows SDK 10.0.18362.0 triggers it.
if(CMAKE_C_COMPILER_ID STREQUAL "MSVC" AND NOT CMAKE_C_COMPILER_VERSION VERSION_LESS 19.28)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -wd5105")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -wd5105")
endif()
if(_CLANG_MSVC_WINDOWS AND "x${CMAKE_CXX_COMPILER_FRONTEND_VARIANT}" STREQUAL "xGNU")
@ -53,6 +59,12 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^parisc")
endif()
endif()
# Use 64-bit off_t on 32-bit Linux
if (CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_SIZEOF_VOID_P EQUAL 4)
# ensure 64bit offsets are used for filesystem accesses for 32bit compilation
add_compile_definitions(_FILE_OFFSET_BITS=64)
endif()
# Workaround for TOC Overflow on ppc64
set(bigTocFlag "")
if(CMAKE_SYSTEM_NAME STREQUAL "AIX" AND
@ -86,7 +98,7 @@ if (CMAKE_CXX_COMPILER_ID STREQUAL SunPro AND
endif()
endif()
foreach(lang C CXX)
foreach(lang IN ITEMS C CXX)
# Suppress warnings from PGI compiler.
if (CMAKE_${lang}_COMPILER_ID STREQUAL "PGI")
set(CMAKE_${lang}_FLAGS "${CMAKE_${lang}_FLAGS} -w")
@ -124,3 +136,12 @@ OFF to disable /MP completely." )
endif()
endif()
endif()
# Get rid of excess -Wunused-but-set-variable on release builds with LCC >= 1.26
foreach(l IN ITEMS C CXX)
if(CMAKE_${l}_COMPILER_ID STREQUAL "LCC" AND NOT CMAKE_${l}_COMPILER_VERSION VERSION_LESS 1.26)
foreach(c IN ITEMS MINSIZEREL RELEASE RELWITHDEBINFO)
string(APPEND "CMAKE_${l}_FLAGS_${c}" " -Wno-unused-but-set-variable")
endforeach()
endif()
endforeach()

View File

@ -1,5 +1,5 @@
CMake - Cross Platform Makefile Generator
Copyright 2000-2019 Kitware, Inc. and Contributors
Copyright 2000-2022 Kitware, Inc. and Contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without
@ -53,6 +53,7 @@ The following individuals and institutions are among the Contributors:
* Clement Creusot <creusot@cs.york.ac.uk>
* Daniel Blezek <blezek@gmail.com>
* Daniel Pfeifer <daniel@pfeifer-mail.de>
* Dawid Wróbel <me@dawidwrobel.com>
* Enrico Scholz <enrico.scholz@informatik.tu-chemnitz.de>
* Eran Ifrah <eran.ifrah@gmail.com>
* Esben Mose Hansen, Ange Optimization ApS
@ -62,11 +63,13 @@ The following individuals and institutions are among the Contributors:
* Helio Chissini de Castro <helio@kde.org>
* Ilya Lavrenov <ilya.lavrenov@itseez.com>
* Insight Software Consortium <insightsoftwareconsortium.org>
* Intel Corporation <www.intel.com>
* Jan Woetzel
* Jordan Williams <jordan@jwillikers.com>
* Julien Schueller
* Kelly Thompson <kgt@lanl.gov>
* Laurent Montel <montel@kde.org>
* Konstantin Podsvirov <konstantin@podsvirov.pro>
* Laurent Montel <montel@kde.org>
* Mario Bensi <mbensi@ipsquad.net>
* Martin Gräßlin <mgraesslin@kde.org>
* Mathieu Malaterre <mathieu.malaterre@gmail.com>
@ -76,6 +79,7 @@ The following individuals and institutions are among the Contributors:
* Michael Hirsch, Ph.D. <www.scivision.co>
* Michael Stürmer
* Miguel A. Figueroa-Villanueva
* Mike Durso <rbprogrammer@gmail.com>
* Mike Jackson
* Mike McQuaid <mike@mikemcquaid.com>
* Nicolas Bock <nicolasbock@gmail.com>
@ -99,6 +103,7 @@ The following individuals and institutions are among the Contributors:
* Sebastian Holtermann <sebholt@xwmw.org>
* Stephen Kelly <steveire@gmail.com>
* Sylvain Joubert <joubert.sy@gmail.com>
* The Qt Company Ltd.
* Thomas Sondergaard <ts@medical-insight.com>
* Tobias Hunger <tobias.hunger@qt.io>
* Todd Gamblin <tgamblin@llnl.gov>

View File

@ -0,0 +1,14 @@
Host And Device Specific Link Options
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.18
When a device link step is involved, which is controlled by
:prop_tgt:`CUDA_SEPARABLE_COMPILATION` and
:prop_tgt:`CUDA_RESOLVE_DEVICE_SYMBOLS` properties and policy :policy:`CMP0105`,
the raw options will be delivered to the host and device link steps (wrapped in
``-Xcompiler`` or equivalent for device link). Options wrapped with
``$<DEVICE_LINK:...>``
:manual:`generator expression <cmake-generator-expressions(7)>` will be used
only for the device link step. Options wrapped with ``$<HOST_LINK:...>``
:manual:`generator expression <cmake-generator-expressions(7)>` will be used
only for the host link step.

View File

@ -11,29 +11,32 @@ The general signature is:
|FIND_XXX| (
<VAR>
name | |NAMES|
[HINTS path1 [path2 ... ENV var]]
[PATHS path1 [path2 ... ENV var]]
[HINTS [path | ENV var]... ]
[PATHS [path | ENV var]... ]
[REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[VALIDATOR function]
[DOC "cache documentation string"]
[NO_CACHE]
[REQUIRED]
[NO_DEFAULT_PATH]
[NO_PACKAGE_ROOT_PATH]
[NO_CMAKE_PATH]
[NO_CMAKE_ENVIRONMENT_PATH]
[NO_SYSTEM_ENVIRONMENT_PATH]
[NO_CMAKE_SYSTEM_PATH]
[NO_CMAKE_INSTALL_PREFIX]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
NO_CMAKE_FIND_ROOT_PATH]
)
This command is used to find a |SEARCH_XXX_DESC|.
A cache entry named by ``<VAR>`` is created to store the result
of this command.
A cache entry, or a normal variable if ``NO_CACHE`` is specified,
named by ``<VAR>`` is created to store the result of this command.
If the |SEARCH_XXX| is found the result is stored in the variable
and the search will not be repeated unless the variable is cleared.
If nothing is found, the result will be
``<VAR>-NOTFOUND``, and the search will be attempted again the
next time |FIND_XXX| is invoked with the same variable.
If nothing is found, the result will be ``<VAR>-NOTFOUND``.
Options include:
@ -50,13 +53,71 @@ Options include:
The ``ENV var`` sub-option reads paths from a system environment
variable.
.. versionchanged:: 3.24
On ``Windows`` platform, it is possible to include registry queries as part
of the directories, using a :ref:`dedicated syntax <Find Using Windows Registry>`.
Such specifications will be ignored on all other platforms.
``REGISTRY_VIEW``
.. versionadded:: 3.24
.. include:: FIND_XXX_REGISTRY_VIEW.txt
``PATH_SUFFIXES``
Specify additional subdirectories to check below each directory
location otherwise considered.
``VALIDATOR``
.. versionadded:: 3.25
Specify a :command:`function` to be called for each candidate item found
(a :command:`macro` cannot be provided, that will result in an error).
Two arguments will be passed to the validator function: the name of a
result variable, and the absolute path to the candidate item. The item
will be accepted and the search will end unless the function sets the
value in the result variable to false in the calling scope. The result
variable will hold a true value when the validator function is entered.
.. parsed-literal::
function(my_check validator_result_var item)
if(NOT item MATCHES ...)
set(${validator_result_var} FALSE PARENT_SCOPE)
endif()
endfunction()
|FIND_XXX| (result NAMES ... VALIDATOR my_check)
Note that if a cached result is used, the search is skipped and any
``VALIDATOR`` is ignored. The cached result is not required to pass the
validation function.
``DOC``
Specify the documentation string for the ``<VAR>`` cache entry.
``NO_CACHE``
.. versionadded:: 3.21
The result of the search will be stored in a normal variable rather than
a cache entry.
.. note::
If the variable is already set before the call (as a normal or cache
variable) then the search will not occur.
.. warning::
This option should be used with caution because it can greatly increase
the cost of repeated configure steps.
``REQUIRED``
.. versionadded:: 3.18
Stop processing with an error message if nothing is found, otherwise
the search will be attempted again the next time |FIND_XXX| is invoked
with the same variable.
If ``NO_DEFAULT_PATH`` is specified, then no additional paths are
added to the search.
If ``NO_DEFAULT_PATH`` is not specified, the search process is as follows:
@ -79,20 +140,21 @@ If ``NO_DEFAULT_PATH`` is not specified, the search process is as follows:
|prefix_XXX_SUBDIR| for each ``<prefix>`` in
:variable:`CMAKE_SYSTEM_PREFIX_PATH`
1. If called from within a find module or any other script loaded by a call to
:command:`find_package(<PackageName>)`, search prefixes unique to the
current package being found. Specifically, look in the
:variable:`<PackageName>_ROOT` CMake variable and the
:envvar:`<PackageName>_ROOT` environment variable.
The package root variables are maintained as a stack, so if called from
nested find modules or config packages, root paths from the parent's find
module or config package will be searched after paths from the current
module or package. In other words, the search order would be
``<CurrentPackage>_ROOT``, ``ENV{<CurrentPackage>_ROOT}``,
``<ParentPackage>_ROOT``, ``ENV{<ParentPackage>_ROOT}``, etc.
This can be skipped if ``NO_PACKAGE_ROOT_PATH`` is passed or by setting
the :variable:`CMAKE_FIND_USE_PACKAGE_ROOT_PATH` to ``FALSE``.
See policy :policy:`CMP0074`.
1. .. versionadded:: 3.12
If called from within a find module or any other script loaded by a call to
:command:`find_package(<PackageName>)`, search prefixes unique to the
current package being found. Specifically, look in the
:variable:`<PackageName>_ROOT` CMake variable and the
:envvar:`<PackageName>_ROOT` environment variable.
The package root variables are maintained as a stack, so if called from
nested find modules or config packages, root paths from the parent's find
module or config package will be searched after paths from the current
module or package. In other words, the search order would be
``<CurrentPackage>_ROOT``, ``ENV{<CurrentPackage>_ROOT}``,
``<ParentPackage>_ROOT``, ``ENV{<ParentPackage>_ROOT}``, etc.
This can be skipped if ``NO_PACKAGE_ROOT_PATH`` is passed or by setting
the :variable:`CMAKE_FIND_USE_PACKAGE_ROOT_PATH` to ``FALSE``.
See policy :policy:`CMP0074`.
* |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX|
@ -130,18 +192,34 @@ If ``NO_DEFAULT_PATH`` is not specified, the search process is as follows:
* |SYSTEM_ENVIRONMENT_PATH_WINDOWS_XXX|
6. Search cmake variables defined in the Platform files
for the current system. This can be skipped if ``NO_CMAKE_SYSTEM_PATH``
is passed or by setting the :variable:`CMAKE_FIND_USE_CMAKE_SYSTEM_PATH`
to ``FALSE``.
for the current system. The searching of ``CMAKE_INSTALL_PREFIX`` and
``CMAKE_STAGING_PREFIX`` can be
skipped if ``NO_CMAKE_INSTALL_PREFIX`` is passed or by setting the
:variable:`CMAKE_FIND_USE_INSTALL_PREFIX` to ``FALSE``. All these locations
can be skipped if ``NO_CMAKE_SYSTEM_PATH`` is passed or by setting the
:variable:`CMAKE_FIND_USE_CMAKE_SYSTEM_PATH` to ``FALSE``.
* |CMAKE_SYSTEM_PREFIX_PATH_XXX|
* |CMAKE_SYSTEM_XXX_PATH|
* |CMAKE_SYSTEM_XXX_MAC_PATH|
The platform paths that these variables contain are locations that
typically include installed software. An example being ``/usr/local`` for
UNIX based platforms.
7. Search the paths specified by the PATHS option
or in the short-hand version of the command.
These are typically hard-coded guesses.
The :variable:`CMAKE_IGNORE_PATH`, :variable:`CMAKE_IGNORE_PREFIX_PATH`,
:variable:`CMAKE_SYSTEM_IGNORE_PATH` and
:variable:`CMAKE_SYSTEM_IGNORE_PREFIX_PATH` variables can also cause some
of the above locations to be ignored.
.. versionadded:: 3.16
Added ``CMAKE_FIND_USE_<CATEGORY>_PATH`` variables to globally disable
various search locations.
.. |FIND_ARGS_XXX| replace:: <VAR> NAMES name
On macOS the :variable:`CMAKE_FIND_FRAMEWORK` and

View File

@ -0,0 +1,41 @@
Specify which registry views must be queried. This option is only meaningful
on ``Windows`` platforms and will be ignored on other ones. When not
specified, the |FIND_XXX_REGISTRY_VIEW_DEFAULT| view is used when the
:policy:`CMP0134` policy is ``NEW``. Refer to :policy:`CMP0134` for the
default view when the policy is ``OLD``.
``64``
Query the 64-bit registry. On 32-bit Windows, it always returns the string
``/REGISTRY-NOTFOUND``.
``32``
Query the 32-bit registry.
``64_32``
Query both views (``64`` and ``32``) and generate a path for each.
``32_64``
Query both views (``32`` and ``64``) and generate a path for each.
``HOST``
Query the registry matching the architecture of the host: ``64`` on 64-bit
Windows and ``32`` on 32-bit Windows.
``TARGET``
Query the registry matching the architecture specified by the
:variable:`CMAKE_SIZEOF_VOID_P` variable. If not defined, fall back to
``HOST`` view.
``BOTH``
Query both views (``32`` and ``64``). The order depends on the following
rules: If the :variable:`CMAKE_SIZEOF_VOID_P` variable is defined, use the
following view depending on the content of this variable:
* ``8``: ``64_32``
* ``4``: ``32_64``
If the :variable:`CMAKE_SIZEOF_VOID_P` variable is not defined, rely on the
architecture of the host:
* 64-bit: ``64_32``
* 32-bit: ``32``

View File

@ -1,3 +1,6 @@
Handling Compiler Driver Differences
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
To pass options to the linker tool, each compiler driver has its own syntax.
The ``LINKER:`` prefix and ``,`` separator can be used to specify, in a portable
way, options to pass to the linker tool. ``LINKER:`` is replaced by the

View File

@ -1,9 +1,15 @@
The final set of compile or link options used for a target is constructed by
Option De-duplication
^^^^^^^^^^^^^^^^^^^^^
The final set of options used for a target is constructed by
accumulating options from the current target and the usage requirements of
its dependencies. The set of options is de-duplicated to avoid repetition.
While beneficial for individual options, the de-duplication step can break
up option groups. For example, ``-D A -D B`` becomes ``-D A B``. One may
specify a group of options using shell-like quoting along with a ``SHELL:``
prefix. The ``SHELL:`` prefix is dropped, and the rest of the option string
is parsed using the :command:`separate_arguments` ``UNIX_COMMAND`` mode.
For example, ``"SHELL:-D A" "SHELL:-D B"`` becomes ``-D A -D B``.
.. versionadded:: 3.12
While beneficial for individual options, the de-duplication step can break
up option groups. For example, ``-option A -option B`` becomes
``-option A B``. One may specify a group of options using shell-like
quoting along with a ``SHELL:`` prefix. The ``SHELL:`` prefix is dropped,
and the rest of the option string is parsed using the
:command:`separate_arguments` ``UNIX_COMMAND`` mode. For example,
``"SHELL:-option A" "SHELL:-option B"`` becomes ``-option A -option B``.

View File

@ -1,16 +1,20 @@
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 for targets in the
current directory and below (whether added before or after this command is
invoked). See documentation of the :prop_dir:`directory <COMPILE_DEFINITIONS>`
and :prop_tgt:`target <COMPILE_DEFINITIONS>` ``COMPILE_DEFINITIONS`` properties.
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

View File

@ -46,3 +46,6 @@ to use the more specific commands :command:`add_compile_definitions`
and :command:`include_directories`.
The command :command:`target_compile_options` adds target-specific options.
The source file property :prop_sf:`COMPILE_OPTIONS` adds options to one
source file.

View File

@ -46,11 +46,19 @@ The options are:
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
@ -59,6 +67,8 @@ The options are:
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
@ -68,6 +78,15 @@ The options 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 Queries>` are not
permitted.
``COMMAND``
Specify the command-line(s) to execute at build time.
If more than one ``COMMAND`` is specified they will be executed in order,
@ -85,56 +104,89 @@ The options are:
* The target is not being cross-compiled (i.e. the
:variable:`CMAKE_CROSSCOMPILING` variable is not set to true).
* 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.
* .. 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 ``TARGET_FILE`` generator expression to refer to the location of
a target later in the command line (i.e. as a command argument rather
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 a target is used as a command to execute or is mentioned in a
generator expression as 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. However this 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.
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.
``DEPENDS``
Specify files on which the command depends. 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.
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`` then the rule will always run.
If ``DEPENDS`` specifies any 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.
Specify files on which the command depends. Each argument is converted
to a dependency as follows:
Arguments to ``DEPENDS`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
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.
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)>`,
@ -153,7 +205,13 @@ The options are:
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.
@ -180,7 +238,15 @@ The options are:
as a file on disk it should be marked with the :prop_sf:`SYMBOLIC`
source file property.
.. 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 Queries>` are not
permitted.
``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>`.
@ -200,14 +266,126 @@ The options are:
If it is a relative path it will be interpreted relative to the
build tree directory corresponding to the current source directory.
Arguments to ``WORKING_DIRECTORY`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
.. versionadded:: 3.13
Arguments to ``WORKING_DIRECTORY`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``DEPFILE``
Specify a ``.d`` depfile for the :generator:`Ninja` generator.
A ``.d`` file holds dependencies usually emitted by the custom
command itself.
Using ``DEPFILE`` with other generators than Ninja is an error.
.. 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.
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.
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.
.. _`add_custom_command(TARGET)`:
Build Events
^^^^^^^^^^^^
@ -249,12 +427,66 @@ of the following is specified:
``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. For backward compatibility reasons, ``POST_BUILD`` is
assumed if no such keyword is given, but projects should explicitly provide
one of the keywords to make clear the behavior they expect.
.. 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 **Visual Studio 2010 (and newer)** generators these command
For **Visual Studio 11 2012 (and newer)** generators these command
lines or custom commands will be omitted for the specific
configuration and no "empty-string-command" will be added.
This allows to add individual build events for every configuration.
.. versionadded:: 3.21
Support for target-dependent generator expressions.
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.

View File

@ -32,6 +32,8 @@ The options are:
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
@ -40,6 +42,8 @@ The options are:
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
@ -49,6 +53,15 @@ The options 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 Queries>` are not
permitted.
``COMMAND``
Specify the command-line(s) to execute at build time.
If more than one ``COMMAND`` is specified they will be executed in order,
@ -64,24 +77,30 @@ The options are:
* The target is not being cross-compiled (i.e. the
:variable:`CMAKE_CROSSCOMPILING` variable is not set to true).
* 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.
* .. 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 ``TARGET_FILE`` generator expression to refer to the location of
a target later in the command line (i.e. as a command argument rather
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 a target is used as a command to execute or is mentioned in a
generator expression as a command argument, a target-level dependency
will be added automatically so that the mentioned target will be built
before this custom target.
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.
@ -95,14 +114,18 @@ The options are:
: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.
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.
.. 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)>`,
@ -111,6 +134,8 @@ The options are:
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.
@ -133,6 +158,8 @@ The options are:
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>`.
@ -142,5 +169,15 @@ The options are:
If it is a relative path it will be interpreted relative to the
build tree directory corresponding to the current source directory.
Arguments to ``WORKING_DIRECTORY`` may use
:manual:`generator expressions <cmake-generator-expressions(7)>`.
.. 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.

View File

@ -8,9 +8,9 @@ Add -D define flags to the compilation of source files.
add_definitions(-DFOO -DBAR ...)
Adds definitions to the compiler command line for targets in the current
directory and below (whether added before or after this command is invoked).
This command can be used to add any flags, but it is intended to add
preprocessor definitions.
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::

View File

@ -17,6 +17,9 @@ 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.
See the ``DEPENDS`` option of :command:`add_custom_target` and
:command:`add_custom_command` commands for adding file-level
dependencies in custom rules. See the :prop_sf:`OBJECT_DEPENDS`

View File

@ -1,8 +1,15 @@
add_executable
--------------
.. only:: html
.. contents::
Add an executable to the project using the specified source files.
Normal Executables
^^^^^^^^^^^^^^^^^^
.. code-block:: cmake
add_executable(<name> [WIN32] [MACOSX_BUNDLE]
@ -10,13 +17,21 @@ Add an executable to the project using the specified source files.
[source1] [source2 ...])
Adds an executable target called ``<name>`` to be built from the source
files listed in the command invocation. (The source files can be omitted
here if they are added later using :command:`target_sources`.) The
files listed in the command invocation. 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
@ -36,16 +51,15 @@ If ``EXCLUDE_FROM_ALL`` is given the corresponding property will be set on
the created target. See documentation of the :prop_tgt:`EXCLUDE_FROM_ALL`
target property for details.
Source arguments to ``add_executable`` may use "generator expressions" with
the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
manual for available expressions. See the :manual:`cmake-buildsystem(7)`
manual for more on defining buildsystem properties.
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
^^^^^^^^^^^^^^^^^^^^
.. code-block:: cmake
@ -65,7 +79,8 @@ whose names begin in ``IMPORTED_``. The most important such property is
the main executable file on disk. See documentation of the ``IMPORTED_*``
properties for more information.
--------------------------------------------------------------------------
Alias Executables
^^^^^^^^^^^^^^^^^
.. code-block:: cmake
@ -74,8 +89,17 @@ properties for more information.
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 a non-``GLOBAL``
:ref:`Imported Target <Imported Targets>` or an ``ALIAS``.
``<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.

View File

@ -14,16 +14,24 @@ Normal Libraries
add_library(<name> [STATIC | SHARED | MODULE]
[EXCLUDE_FROM_ALL]
[source1] [source2 ...])
[<source>...])
Adds a library target called ``<name>`` to be built from the source files
listed in the command invocation. (The source files can be omitted here
if they are added later using :command:`target_sources`.) The ``<name>``
listed in the command invocation. 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`.
``STATIC``, ``SHARED``, or ``MODULE`` may be given to specify the type of
library to be created. ``STATIC`` libraries are archives of object files
for use when linking other targets. ``SHARED`` libraries are linked
@ -34,9 +42,13 @@ type is ``STATIC`` or ``SHARED`` based on whether the current value of the
variable :variable:`BUILD_SHARED_LIBS` is ``ON``. For ``SHARED`` and
``MODULE`` libraries the :prop_tgt:`POSITION_INDEPENDENT_CODE` target
property is set to ``ON`` automatically.
A ``SHARED`` or ``STATIC`` library may be marked with the :prop_tgt:`FRAMEWORK`
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.
@ -55,57 +67,19 @@ If ``EXCLUDE_FROM_ALL`` is given the corresponding property will be set on
the created target. See documentation of the :prop_tgt:`EXCLUDE_FROM_ALL`
target property for details.
Source arguments to ``add_library`` may use "generator expressions" with
the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
manual for available expressions. See the :manual:`cmake-buildsystem(7)`
manual for more on defining buildsystem properties.
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 Libraries
^^^^^^^^^^^^^^^^^^
.. code-block:: cmake
add_library(<name> <SHARED|STATIC|MODULE|OBJECT|UNKNOWN> IMPORTED
[GLOBAL])
An :ref:`IMPORTED library target <Imported Targets>` references a library
file located outside the project. No rules are generated to build it, and
the :prop_tgt:`IMPORTED` target property is ``True``. The target name has
scope in the directory in which it is created and below, but the ``GLOBAL``
option extends visibility. It may be referenced like any target built
within the project. ``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_``.
The most important properties are:
* :prop_tgt:`IMPORTED_LOCATION` (and its per-configuration
variant :prop_tgt:`IMPORTED_LOCATION_<CONFIG>`) which specifies the
location of the main library file on disk.
* :prop_tgt:`IMPORTED_OBJECTS` (and :prop_tgt:`IMPORTED_OBJECTS_<CONFIG>`)
for object libraries, specifies the locations of object files on disk.
* :prop_tgt:`PUBLIC_HEADER` files to be installed during :command:`install` invocation
See documentation of the ``IMPORTED_*`` and ``INTERFACE_*`` properties
for more information.
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 Libraries
^^^^^^^^^^^^^^^^
.. code-block:: cmake
add_library(<name> OBJECT <src>...)
add_library(<name> OBJECT [<source>...])
Creates an :ref:`Object Library <Object Libraries>`. An object library
compiles source files but does not archive or link their object files into a
@ -129,38 +103,22 @@ systems (such as Xcode) may not like targets that have only object files, so
consider adding at least one real source file to any target that references
``$<TARGET_OBJECTS:objlib>``.
Alias Libraries
^^^^^^^^^^^^^^^
.. code-block:: cmake
add_library(<name> ALIAS <target>)
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 a non-``GLOBAL`` :ref:`Imported Target <Imported Targets>` or an
``ALIAS``.
``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.
.. versionadded:: 3.12
Object libraries can be linked to with :command:`target_link_libraries`.
Interface Libraries
^^^^^^^^^^^^^^^^^^^
.. code-block:: cmake
add_library(<name> INTERFACE [IMPORTED [GLOBAL]])
add_library(<name> INTERFACE)
Creates an :ref:`Interface Library <Interface Libraries>`. An ``INTERFACE``
library target does not directly create build output, though it may
have properties set on it and it may be installed, exported and
imported. Typically the ``INTERFACE_*`` properties are populated on
the interface target using the commands:
Creates an :ref:`Interface Library <Interface Libraries>`.
An ``INTERFACE`` library target does not compile sources and does
not produce a library artifact on disk. 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)`,
@ -173,10 +131,133 @@ the interface target using the commands:
and then it is used as an argument to :command:`target_link_libraries`
like any other target.
An ``INTERFACE`` :ref:`Imported Target <Imported Targets>` may also be
created with this signature. An ``IMPORTED`` library target references a
library defined outside the project. The target name has scope in the
directory in which it is created and below, but the ``GLOBAL`` option
extends visibility. It may be referenced like any target built within
the project. ``IMPORTED`` libraries are useful for convenient reference
from commands like :command:`target_link_libraries`.
An interface library created with the above signature has no source files
itself and is not included as a target in the generated buildsystem.
.. 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.
.. versionadded:: 3.19
An interface library target may be created with source files:
.. code-block:: cmake
add_library(<name> INTERFACE [<source>...] [EXCLUDE_FROM_ALL])
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.
.. 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.
.. _`add_library imported libraries`:
Imported Libraries
^^^^^^^^^^^^^^^^^^
.. code-block:: cmake
add_library(<name> <type> IMPORTED [GLOBAL])
Creates an :ref:`IMPORTED library target <Imported Targets>` called ``<name>``.
No rules are generated to build it, and the :prop_tgt:`IMPORTED` target
property is ``True``. The target name has scope in the directory in which
it is created and below, but the ``GLOBAL`` option extends visibility.
It may be referenced like any target built within the project.
``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_``.
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.
See documentation of the ``IMPORTED_*`` and ``INTERFACE_*`` properties
for more information.
Alias Libraries
^^^^^^^^^^^^^^^
.. code-block:: cmake
add_library(<name> ALIAS <target>)
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.

View File

@ -1,6 +1,8 @@
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.
@ -26,6 +28,8 @@ the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
manual for available expressions. See the :manual:`cmake-buildsystem(7)`
manual for more on defining buildsystem properties.
.. include:: DEVICE_LINK_OPTIONS.txt
.. include:: OPTIONS_SHELL.txt
.. include:: LINK_OPTIONS_LINKER.txt

View File

@ -5,7 +5,7 @@ Add a subdirectory to the build.
.. code-block:: cmake
add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL])
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
@ -33,3 +33,10 @@ dependencies supersede this exclusion. If a target built by the
parent project depends on a target in the subdirectory, the dependee
target will be included in the parent project build system to satisfy
the dependency.
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 target
created in that subdirectory. The include directories of targets with
:prop_tgt:`SYSTEM` set to true will be treated as ``SYSTEM`` when
compiling consumers.

View File

@ -10,8 +10,9 @@ Add a test to the project to be run by :manual:`ctest(1)`.
[WORKING_DIRECTORY <dir>]
[COMMAND_EXPAND_LISTS])
Adds a test called ``<name>``. The test name may not contain spaces,
quotes, or other characters special in CMake syntax. The options are:
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`. The options are:
``COMMAND``
Specify the test command-line. If ``<command>`` specifies an
@ -19,6 +20,9 @@ quotes, or other characters special in CMake syntax. The options are:
automatically be replaced by the location of the executable created
at build time.
The command may be specified using
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``CONFIGURATIONS``
Restrict execution of the test only to the named configurations.
@ -29,7 +33,12 @@ quotes, or other characters special in CMake syntax. The options are:
directory set to the build directory corresponding to the
current source directory.
The working directory may be specified using
:manual:`generator expressions <cmake-generator-expressions(7)>`.
``COMMAND_EXPAND_LISTS``
.. versionadded:: 3.16
Lists in ``COMMAND`` arguments will be expanded, including those
created with
:manual:`generator expressions <cmake-generator-expressions(7)>`.
@ -42,16 +51,20 @@ unless the :prop_test:`PASS_REGULAR_EXPRESSION`,
:prop_test:`FAIL_REGULAR_EXPRESSION` or
:prop_test:`SKIP_REGULAR_EXPRESSION` test property is used.
The ``COMMAND`` and ``WORKING_DIRECTORY`` options may use "generator
expressions" with the syntax ``$<...>``. See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
.. versionadded:: 3.16
Added :prop_test:`SKIP_REGULAR_EXPRESSION` property.
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`.
Example usage:
.. code-block:: cmake
add_test(NAME mytest
COMMAND testDriver --config $<CONFIGURATION>
COMMAND testDriver --config $<CONFIG>
--exe $<TARGET_FILE:myexe>)
This creates a test ``mytest`` whose command runs a ``testDriver`` tool
@ -67,10 +80,15 @@ file produced by target ``myexe``.
---------------------------------------------------------------------
This command also supports a simpler, but less flexible, signature:
.. code-block:: cmake
add_test(<name> <command> [<arg>...])
Add a test called ``<name>`` with the given command-line. Unlike
the above ``NAME`` signature no transformation is performed on the
command-line to support target names or generator expressions.
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.

76
Help/command/block.rst Normal file
View File

@ -0,0 +1,76 @@
block
-----
.. versionadded:: 3.25
Evaluate a group of commands with a dedicated variable and/or policy scope.
.. code-block:: cmake
block([SCOPE_FOR [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.
``POLICIES``
Create a new policy scope. This is equivalent to
:command:`cmake_policy(PUSH)`.
``VARIABLES``
Create a new variable scope.
If ``SCOPE_FOR`` is not specified, this is equivalent to:
.. code-block:: cmake
block(SCOPE_FOR VARIABLES POLICIES)
``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")
block(PROPAGATE var1 var2)
set(var1 "VALUE1")
unset(var2)
endblock()
# Now var1 holds VALUE1, and var2 is unset
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`

View File

@ -8,23 +8,29 @@ This is mainly intended for internal use by the :module:`CTest` module.
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>] [--target <target>...] [-- -i]
<cmake> --build . [--config <config>] [--parallel <parallel>] [--target <target>...] [-- -i]
where ``<cmake>`` is the location of the :manual:`cmake(1)` command-line
tool, and ``<config>`` and ``<target>`` are the values provided to the
``CONFIGURATION`` and ``TARGET`` options, if any. The trailing ``-- -i``
option is added for :ref:`Makefile Generators` if policy :policy:`CMP0061`
is not set to ``NEW``.
tool, and ``<config>``, ``<parallel>`` and ``<target>`` are the values
provided to the ``CONFIGURATION``, ``PARALLEL_LEVEL`` and ``TARGET``
options, if any. The trailing ``-- -i`` option is added for
:ref:`Makefile Generators` if policy :policy:`CMP0061` is not set to
``NEW``.
When invoked, this ``cmake --build`` command line will launch the
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
:option:`--parallel <cmake--build --parallel>` flag.
.. code-block:: cmake
build_command(<cachevariable> <makecommand>)
@ -33,7 +39,7 @@ 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 ``--target`` option.
above but without the :option:`--target <cmake--build --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.

View File

@ -1,9 +1,23 @@
cmake_host_system_information
-----------------------------
Query host system specific information.
Query various host system information.
.. code-block:: cmake
Synopsis
^^^^^^^^
.. parsed-literal::
`Query host system specific information`_
cmake_host_system_information(RESULT <variable> QUERY <key> ...)
`Query Windows registry`_
cmake_host_system_information(RESULT <variable> QUERY WINDOWS_REGISTRY <key> ...)
Query host system specific information
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
::
cmake_host_system_information(RESULT <variable> QUERY <key> ...)
@ -13,38 +27,370 @@ queried. The list of queried values is stored in ``<variable>``.
``<key>`` can be one of the following values:
============================= ================================================
Key Description
============================= ================================================
``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`` One if processor is 64Bit
``HAS_FPU`` One if processor has floating point unit
``HAS_MMX`` One if processor supports MMX instructions
``HAS_MMX_PLUS`` One if processor supports Ext. MMX instructions
``HAS_SSE`` One if processor supports SSE instructions
``HAS_SSE2`` One if processor supports SSE2 instructions
``HAS_SSE_FP`` One if processor supports SSE FP instructions
``HAS_SSE_MMX`` One if processor supports SSE MMX instructions
``HAS_AMD_3DNOW`` One if processor supports 3DNow instructions
``HAS_AMD_3DNOW_PLUS`` One if processor supports 3DNow+ instructions
``HAS_IA64`` One if IA64 processor emulating x86
``HAS_SERIAL_NUMBER`` One if processor has serial number
``PROCESSOR_SERIAL_NUMBER`` Processor serial number
``PROCESSOR_NAME`` Human readable processor name
``PROCESSOR_DESCRIPTION`` Human readable full processor description
``OS_NAME`` See :variable:`CMAKE_HOST_SYSTEM_NAME`
``OS_RELEASE`` The OS sub-type e.g. on Windows ``Professional``
``OS_VERSION`` The OS build ID
``OS_PLATFORM`` See :variable:`CMAKE_HOST_SYSTEM_PROCESSOR`
============================= ================================================
``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
``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
``OS_NAME``
.. versionadded:: 3.10
See :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`
``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 to his script(s) to the 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
# 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)
.. rubric:: Footnotes
.. [#mebibytes] One MiB (mebibyte) is equal to 1024x1024 bytes.
.. _man 5 os-release: https://www.freedesktop.org/software/systemd/man/os-release.html
.. _various distribution-specific files: http://linuxmafia.com/faq/Admin/release-files.html
.. _Query Windows registry:
Query Windows registry
^^^^^^^^^^^^^^^^^^^^^^
.. versionadded:: 3.24
::
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>])
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.

View File

@ -0,0 +1,521 @@
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>)
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
^^^^^^^^^^^^^^^^
.. _CALL:
.. code-block:: cmake
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
^^^^^^^^^^^^^^^
.. _EVAL:
.. code-block:: cmake
cmake_language(EVAL CODE <code>...)
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
.. _DEFER:
.. code-block:: cmake
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 ``Cancelled 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
.. _SET_DEPENDENCY_PROVIDER:
.. _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>`.
.. code-block:: cmake
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.
.. 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_MAKEAVAILABE_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
.. _GET_MESSAGE_LOG_LEVEL:
.. _query_message_log_level:
.. code-block:: cmake
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
:option:`--log-level <cmake --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.

View File

@ -5,23 +5,29 @@ Require a minimum version of cmake.
.. code-block:: cmake
cmake_minimum_required(VERSION <min>[...<max>] [FATAL_ERROR])
cmake_minimum_required(VERSION <min>[...<policy_max>] [FATAL_ERROR])
.. versionadded:: 3.12
The optional ``<policy_max>`` version.
Sets the minimum required version of cmake for a project.
Also updates the policy settings as explained below.
``<min>`` and the optional ``<max>`` are each CMake versions of the form
``major.minor[.patch[.tweak]]``, and the ``...`` is literal.
``<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 ``<max>`` version, if specified, must be at least the
``<min>`` version and affects policy settings as described below.
The optional ``<policy_max>`` version, if specified, must be at least the
``<min>`` version and affects policy settings as described in `Policy Settings`_.
If the running version of CMake is older than 3.12, the extra ``...``
dots will be seen as version component separators, resulting in the
``...<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.
@ -34,8 +40,15 @@ with an error instead of just a warning.
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. Such calls
should not be made with the intention of having global effects.
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 Settings`:
Policy Settings
^^^^^^^^^^^^^^^

View File

@ -11,6 +11,10 @@ Parse function or macro arguments.
cmake_parse_arguments(PARSE_ARGV <N> <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
@ -19,11 +23,12 @@ respective options.
The first signature reads processes arguments passed in the ``<args>...``.
This may be used in either a :command:`macro` or a :command:`function`.
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:: 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.
The ``<options>`` argument contains all options for the respective macro,
i.e. keywords which can be used when calling the macro without any value
@ -38,12 +43,11 @@ The ``<multi_value_keywords>`` argument contains all keywords for this
macro which can be followed by more than one value, like e.g. the
``TARGETS`` or ``FILES`` keywords of the :command:`install` command.
.. note::
All keywords shall be unique. I.e. every keyword shall only be specified
once in either ``<options>``, ``<one_value_keywords>`` or
``<multi_value_keywords>``. A warning will be emitted if uniqueness is
violated.
.. versionchanged:: 3.5
All keywords shall be unique. I.e. every keyword shall only be specified
once in either ``<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
@ -59,10 +63,12 @@ All remaining arguments are collected in a variable
were recognized. This can be checked afterwards to see
whether your macro was called with unrecognized parameters.
``<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.
.. 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.
Consider the following example macro, ``my_install()``, which takes similar
arguments to the real :command:`install` command:

798
Help/command/cmake_path.rst Normal file
View File

@ -0,0 +1,798 @@
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> :ref:`ROOT_NAME <GET_ROOT_NAME>` <out-var>)
cmake_path(`GET`_ <path-var> :ref:`ROOT_DIRECTORY <GET_ROOT_DIRECTORY>` <out-var>)
cmake_path(`GET`_ <path-var> :ref:`ROOT_PATH <GET_ROOT_PATH>` <out-var>)
cmake_path(`GET`_ <path-var> :ref:`FILENAME <GET_FILENAME>` <out-var>)
cmake_path(`GET`_ <path-var> :ref:`EXTENSION <GET_EXTENSION>` [LAST_ONLY] <out-var>)
cmake_path(`GET`_ <path-var> :ref:`STEM <GET_STEM>` [LAST_ONLY] <out-var>)
cmake_path(`GET`_ <path-var> :ref:`RELATIVE_PART <GET_RELATIVE_PART>` <out-var>)
cmake_path(`GET`_ <path-var> :ref:`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>)
cmake_path(`COMPARE`_ <input1> <OP> <input2> <out-var>)
`Modification`_
cmake_path(:ref:`SET <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`_ <out-var> [NORMALIZE])
cmake_path(`CONVERT`_ <input> `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
^^^^^^^^^^^^^^^^^^^^^^^^
While a path can be created with care using an ordinary :command:`set`
command, it is recommended to use :ref:`cmake_path(SET) <cmake_path-SET>`
instead, as it automatically converts the path to the required form where
required. The :ref:`cmake_path(APPEND) <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.
.. _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:
.. _GET_ROOT_NAME:
.. _GET_ROOT_DIRECTORY:
.. _GET_ROOT_PATH:
.. _GET_FILENAME:
.. _GET_EXTENSION:
.. _GET_STEM:
.. _GET_RELATIVE_PART:
.. _GET_PARENT_PATH:
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.
::
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>)
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 `HAS_RELATIVE_PART`_ subcommand 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 `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 dotMorePath EXTENSION someMoreExt)
cmake_path(GET dotMorePath 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 ``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.
.. _HAS_ROOT_NAME:
.. _HAS_ROOT_DIRECTORY:
.. _HAS_ROOT_PATH:
.. _HAS_FILENAME:
.. _HAS_EXTENSION:
.. _HAS_STEM:
.. _HAS_RELATIVE_PART:
.. _HAS_PARENT_PATH:
::
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>`.
.. _IS_ABSOLUTE:
::
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 ``HAS_ROOT_DIRECTORY`` can be true.
.. _IS_RELATIVE:
::
cmake_path(IS_RELATIVE <path-var> <out-var>)
This will store the opposite of ``IS_ABSOLUTE`` in ``<out-var>``.
.. _IS_PREFIX:
::
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 COMPARE:
.. _COMPARE:
::
cmake_path(COMPARE <input1> EQUAL <input2> <out-var>)
cmake_path(COMPARE <input1> NOT_EQUAL <input2> <out-var>)
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
^^^^^^^^^^^^
.. _cmake_path-SET:
::
cmake_path(SET <path-var> [NORMALIZE] <input>)
Assign 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"
.. _APPEND:
::
cmake_path(APPEND <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
Append 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>
.. _APPEND_STRING:
::
cmake_path(APPEND_STRING <path-var> [<input>...] [OUTPUT_VARIABLE <out-var>])
Append all the ``<input>`` arguments to the ``<path-var>`` without adding any
``directory-separator``.
.. _REMOVE_FILENAME:
::
cmake_path(REMOVE_FILENAME <path-var> [OUTPUT_VARIABLE <out-var>])
Removes the :ref:`filename <FILENAME_DEF>` component (as returned by
:ref:`GET ... FILENAME <GET_FILENAME>`) from ``<path-var>``. After removal,
any trailing ``directory-separator`` is left alone, if present.
If ``OUTPUT_VARIABLE`` is not given, then after this function returns,
`HAS_FILENAME`_ returns false for ``<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 \"${result}\"")
Output::
First path is "/a/"
Second path is "/a/"
.. _REPLACE_FILENAME:
::
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.
`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()
.. _REMOVE_EXTENSION:
::
cmake_path(REMOVE_EXTENSION <path-var> [LAST_ONLY]
[OUTPUT_VARIABLE <out-var>])
Removes the :ref:`extension <EXTENSION_DEF>`, if any, from ``<path-var>``.
.. _REPLACE_EXTENSION:
::
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")
.. _Path Generation:
Generation
^^^^^^^^^^
.. _NORMAL_PATH:
::
cmake_path(NORMAL_PATH <path-var> [OUTPUT_VARIABLE <out-var>])
Normalize ``<path-var>`` according the steps described in :ref:`Normalization`.
.. _cmake_path-RELATIVE_PATH:
.. _RELATIVE_PATH:
::
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/w/cpp/filesystem/path/lexically_normal>`_.
.. _ABSOLUTE_PATH:
::
cmake_path(ABSOLUTE_PATH <path-var> [BASE_DIRECTORY <input>] [NORMALIZE]
[OUTPUT_VARIABLE <out-var>])
If ``<path-var>`` is a relative path (`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.
Native Conversion
^^^^^^^^^^^^^^^^^
For commands in this section, *native* refers to the host platform, not the
target platform when cross-compiling.
.. _cmake_path-NATIVE_PATH:
.. _NATIVE_PATH:
::
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.
.. _CONVERT:
.. _cmake_path-TO_CMAKE_PATH_LIST:
.. _TO_CMAKE_PATH_LIST:
::
cmake_path(CONVERT <input> TO_CMAKE_PATH_LIST <out-var> [NORMALIZE])
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 cmake-style list
separated by ``;`` characters (on non-Windows platforms, this essentially
means ``:`` separators are replaced with ``;``). The result of the
conversion is stored in the ``<out-var>`` variable.
When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` before the conversion.
.. note::
Unlike most other ``cmake_path()`` subcommands, the ``CONVERT`` subcommand
takes a literal string as input, not the name of a variable.
.. _cmake_path-TO_NATIVE_PATH_LIST:
.. _TO_NATIVE_PATH_LIST:
::
cmake_path(CONVERT <input> TO_NATIVE_PATH_LIST <out-var> [NORMALIZE])
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 cmake-style list. A list will be
converted into a native search path (``;``-separated on Windows,
``:``-separated on other platforms). The result of the conversion is
stored in the ``<out-var>`` variable.
When the ``NORMALIZE`` option is specified, the path is :ref:`normalized
<Normalization>` before the conversion.
.. 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
^^^^^^^
.. _HASH:
::
cmake_path(HASH <path-var> <out-var>)
Compute a hash value of ``<path-var>`` such that for two paths ``p1`` and
``p2`` that compare equal (:ref:`COMPARE ... EQUAL <COMPARE>`), 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.

View File

@ -28,6 +28,9 @@ encourage projects to set policies based on CMake versions:
cmake_policy(VERSION <min>[...<max>])
.. versionadded:: 3.12
The optional ``<max>`` version.
``<min>`` and the optional ``<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.
@ -100,6 +103,47 @@ Calls to the :command:`cmake_minimum_required(VERSION)`,
``cmake_policy(VERSION)``, or ``cmake_policy(SET)`` commands
influence only the current top of the policy stack.
.. versionadded:: 3.25
The :command:`block` and :command:`endblock` commands offer a more flexible
and more secure way to manage the policy stack. The pop action is done
automatically when the :command:`endblock` command is executed, so it avoid
to call the :command:`cmake_policy(POP)` command before each
:command:`return` command.
.. 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

View File

@ -6,6 +6,8 @@ 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] ])
@ -34,24 +36,48 @@ or
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.
Input file lines of the form ``#cmakedefine01 VAR`` will be replaced with
either ``#define VAR 1`` or ``#define VAR 0`` similarly.
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:
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
# cmakedefine VAR
# cmakedefine01 VAR
#cmakedefine01 VAR
will be replaced, if ``VAR`` is defined, with
will be replaced with either
.. code-block:: c
# define VAR
# define VAR 1
#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 ... 0``,
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
If the input file is modified the build system will re-run CMake to
re-configure the file and generate the build system again.
@ -70,6 +96,29 @@ The arguments are:
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

View File

@ -1,14 +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 a block
in a :command:`foreach` or :command:`while` loop, and start at the top of
the next iteration.
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.

View File

@ -7,6 +7,7 @@ Perform the :ref:`CTest Build Step` as a :ref:`Dashboard Client`.
ctest_build([BUILD <build-dir>] [APPEND]
[CONFIGURATION <config>]
[PARALLEL_LEVEL <parallel>]
[FLAGS <flags>]
[PROJECT_NAME <project-name>]
[TARGET <target-name>]
@ -39,18 +40,28 @@ The options are:
``CONFIGURATION <config>``
Specify the build configuration (e.g. ``Debug``). If not
specified the ``CTEST_BUILD_CONFIGURATION`` variable will be checked.
Otherwise the ``-C <cfg>`` option given to the :manual:`ctest(1)`
command will be used, if any.
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
``-j`` option of ``make``. See the :module:`ProcessorCount` module
for an example.
``PROJECT_NAME <project-name>``
Ignored. This was once used but is no longer needed.
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
@ -68,10 +79,14 @@ The options are:
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

View File

@ -37,10 +37,14 @@ The options are:
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 ctest 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.

View File

@ -37,10 +37,14 @@ The options are:
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 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 indicating how many
lines of code were covered is unaffected by this option.

View File

@ -17,10 +17,15 @@ Perform the :ref:`CTest MemCheck Step` as a :ref:`Dashboard Client`.
[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>]
[DEFECT_COUNT <defect-count-var>]
[QUIET]
)
@ -35,4 +40,6 @@ 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.

View File

@ -1,15 +1,15 @@
ctest_run_script
----------------
runs a ctest -S script
runs a :option:`ctest -S` script
::
ctest_run_script([NEW_PROCESS] script_file_name script_file_name1
script_file_name2 ... [RETURN_VALUE var])
Runs a script or scripts much like if it was run from ctest -S. If no
argument is provided then the current script is run using the current
Runs a script or scripts much like if it was run from :option:`ctest -S`.
If no argument is provided then the current script is run using the current
settings of the variables. If ``NEW_PROCESS`` is specified then each
script will be run in a separate process.If ``RETURN_VALUE`` is specified
the return value of the last script run will be put into ``var``.

View File

@ -29,8 +29,11 @@ The parameters are as follows:
``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. This replaces the deprecated option ``TRACK``. Despite the name
change its behavior is unchanged.
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
@ -42,7 +45,7 @@ The parameters are as follows:
ctest_start(Experimental GROUP GroupExperimental)
Later, in another ``ctest -S`` script:
Later, in another :option:`ctest -S` script:
.. code-block:: cmake
@ -56,6 +59,8 @@ The parameters are as follows:
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.

View File

@ -30,7 +30,8 @@ The options are:
Build = ctest_build results, in Build.xml
Test = ctest_test results, in Test.xml
Coverage = ctest_coverage results, in Coverage.xml
MemCheck = ctest_memcheck results, in DynamicAnalysis.xml
MemCheck = ctest_memcheck results, in DynamicAnalysis.xml and
DynamicAnalysis-Test.xml
Notes = Files listed by CTEST_NOTES_FILES, in Notes.xml
ExtraFiles = Files listed by CTEST_EXTRA_SUBMIT_FILES
Upload = Files prepared for upload by ctest_upload(), in Upload.xml
@ -42,14 +43,20 @@ The options are:
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
@ -73,20 +80,27 @@ The options are:
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 ctest 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
::
ctest_submit(CDASH_UPLOAD <file> [CDASH_UPLOAD_TYPE <type>]
[SUBMIT_URL <url>]
[BUILD_ID <result-var>]
[HTTPHEADER <header>]
[RETRY_COUNT <count>]
[RETRY_DELAY <delay>]
@ -99,6 +113,19 @@ 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 accepts the ``SUBMIT_URL``, ``BUILD_ID``, ``HTTPHEADER``,
``RETRY_COUNT``, ``RETRY_DELAY``, ``RETURN_VALUE`` and ``QUIET`` options
as described above.
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.

View File

@ -20,12 +20,19 @@ Perform the :ref:`CTest Test Step` as a :ref:`Dashboard Client`.
[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>]
[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.
@ -66,6 +73,8 @@ The options are:
Tests not matching this expression are excluded.
``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
@ -74,9 +83,13 @@ The options are:
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>``
@ -84,21 +97,52 @@ The options are:
be run in parallel.
``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 ``--test-load`` command-line argument to :manual:`ctest(1)`.
See also the ``TestLoad`` setting in the :ref:`CTest Test Step`.
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.
@ -107,14 +151,162 @@ The options are:
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 ctest 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.
``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`
and :variable:`CTEST_CUSTOM_MAXIMUM_FAILED_TEST_OUTPUT_SIZE` variables.
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
:option:`--test-output-size-passed <ctest --test-output-size-passed>`,
:option:`--test-output-size-failed <ctest --test-output-size-failed>`, and
:option:`--test-output-truncation <ctest --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.

View File

@ -24,10 +24,14 @@ The options are:
updated or ``-1`` on error.
``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 ctest from returning non-zero if an error occurs.
``QUIET``
.. versionadded:: 3.3
Tell CTest to suppress most non-error messages that it would
have otherwise printed to the console. CTest will still report
the new revision of the repository and any conflicting files

View File

@ -14,9 +14,13 @@ The options are:
dashboard server.
``QUIET``
.. versionadded:: 3.3
Suppress any CTest-specific non-error output that would have been
printed to the console 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 ctest from returning non-zero if an error occurs.

View File

@ -8,15 +8,18 @@ Define and document custom properties.
define_property(<GLOBAL | DIRECTORY | TARGET | SOURCE |
TEST | VARIABLE | CACHED_VARIABLE>
PROPERTY <name> [INHERITED]
BRIEF_DOCS <brief-doc> [docs...]
FULL_DOCS <full-doc> [docs...])
[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. This is primarily useful to associate
documentation with property names that may be retrieved with the
:command:`get_property` command. The first argument determines the kind of
scope in which the property should be used. It must be one of the
following:
: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:
::
@ -55,5 +58,18 @@ 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.
Corresponding options to the :command:`get_property` command will retrieve
the 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.

View File

@ -1,15 +1,29 @@
enable_language
---------------
Enable a language (CXX/C/OBJC/OBJCXX/Fortran/etc)
Enable languages (CXX/C/OBJC/OBJCXX/Fortran/etc)
.. code-block:: cmake
enable_language(<lang> [OPTIONAL] )
enable_language(<lang>... [OPTIONAL])
Enables support for the named language in CMake. This is
the same as the :command:`project` command but does not create any of the extra
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 project command. Example languages
are ``CXX``, ``C``, ``CUDA``, ``OBJC``, ``OBJCXX``, ``Fortran``, and ``ASM``.
are ``CXX``, ``C``, ``CUDA``, ``OBJC``, ``OBJCXX``, ``Fortran``,
``HIP``, ``ISPC``, and ``ASM``.
.. versionadded:: 3.8
Added ``CUDA`` support.
.. versionadded:: 3.16
Added ``OBJC`` and ``OBJCXX`` support.
.. versionadded:: 3.18
Added ``ISPC`` support.
.. versionadded:: 3.21
Added ``HIP`` support.
If enabling ``ASM``, enable it last so that CMake can check whether
compilers for other languages like ``C`` work for assembly too.

11
Help/command/endblock.rst Normal file
View File

@ -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()

View File

@ -21,7 +21,10 @@ Execute one or more child processes.
[COMMAND_ECHO <where>]
[OUTPUT_STRIP_TRAILING_WHITESPACE]
[ERROR_STRIP_TRAILING_WHITESPACE]
[ENCODING <name>])
[ENCODING <name>]
[ECHO_OUTPUT_VARIABLE]
[ECHO_ERROR_VARIABLE]
[COMMAND_ERROR_IS_FATAL <ANY|LAST>])
Runs the given sequence of one or more commands.
@ -34,8 +37,15 @@ Options:
``COMMAND``
A child process command line.
CMake executes the child process using operating system APIs directly.
All arguments are passed VERBATIM to the child process.
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.
* On Windows platforms, the command line is encoded as a string such
that child processes using ``CommandLineToArgvW`` will decode the
original arguments.
No intermediate shell is used, so shell operators such as ``>``
are treated as normal arguments.
(Use the ``INPUT_*``, ``OUTPUT_*``, and ``ERROR_*`` options to
@ -59,6 +69,8 @@ Options:
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
@ -72,19 +84,26 @@ Options:
``INPUT_FILE, OUTPUT_FILE``, ``ERROR_FILE``
The file named will be attached to the standard input of the first
process, standard output of the last process, or standard error of
all processes, respectively. If the same file is named for both
output and error then it will be used for both.
all processes, respectively.
.. versionadded:: 3.3
If the same file is named for both output and error then it will be used
for both.
``OUTPUT_QUIET``, ``ERROR_QUIET``
The standard output or standard error results will be quietly ignored.
``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:
@ -101,9 +120,37 @@ Options:
``OEM``
Use the original equipment manufacturer (OEM) code page.
``UTF8`` or ``UTF-8``
Use the UTF-8 codepage. Prior to CMake 3.11.0, only ``UTF8`` was accepted
for this encoding. In CMake 3.11.0, ``UTF-8`` was added for consistency with
the `UTF-8 RFC <https://www.ietf.org/rfc/rfc3629>`_ naming convention.
Use the UTF-8 codepage.
.. versionadded:: 3.11
Accept ``UTF-8`` spelling for consistency with the
`UTF-8 RFC <https://www.ietf.org/rfc/rfc3629>`_ naming convention.
``ECHO_OUTPUT_VARIABLE``, ``ECHO_ERROR_VARIABLE``
.. versionadded:: 3.18
The standard output or standard error will not be exclusively redirected to
the configured variables.
The output will be duplicated, it will be sent into the configured variables
and also on standard output or standard error.
This is analogous to the ``tee`` Unix command.
``COMMAND_ERROR_IS_FATAL <ANY|LAST>``
.. 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.
If more than one ``OUTPUT_*`` or ``ERROR_*`` option is given for the
same pipe the precedence is not specified.

View File

@ -1,44 +1,73 @@
export
------
Export targets from the build tree for use by outside projects.
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>)
Exporting Targets
^^^^^^^^^^^^^^^^^
.. _`export(TARGETS)`:
.. _TARGETS:
.. code-block:: cmake
export(EXPORT <export-name> [NAMESPACE <namespace>] [FILE <filename>])
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 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. If the ``NAMESPACE``
option is given the ``<namespace>`` string will be prepended to all target
names written to the file.
Target installations are associated with the export ``<export-name>``
using the ``EXPORT`` option of the :command:`install(TARGETS)` command.
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 installation tree.
export targets from an install tree.
The properties set on the generated IMPORTED targets will have the
same values as the final values of the input TARGETS.
The options are:
.. code-block:: cmake
``NAMESPACE <namespace>``
Prepend the ``<namespace>`` string to all target names written to the file.
export(TARGETS [target1 [target2 [...]]] [NAMESPACE <namespace>]
[APPEND] FILE <filename> [EXPORT_LINK_INTERFACE_LIBRARIES])
``APPEND``
Append to the file instead of overwriting it. This can be used to
incrementally export multiple targets to the same file.
This signature is similar to the ``EXPORT`` signature, but targets are listed
explicitly rather than specified as an export-name. If the APPEND option is
given the generated code will be appended to the file instead of overwriting it.
The EXPORT_LINK_INTERFACE_LIBRARIES keyword, if present, causes the
contents of the properties matching
``(IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)?`` to be exported, when
policy CMP0022 is NEW. If a library target is included in the export
but a target to which it links is not included the behavior is
unspecified.
``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>``
.. note ::
Experimental. Gated by ``CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API``
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 `export(EXPORT)`_ signature
to automatically export the same targets from the build tree as
:command:`install(EXPORT)` would from an install tree.
.. note::
@ -49,6 +78,51 @@ unspecified.
transitive usage requirements of other targets that link to the
object libraries in their implementation.
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)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. _`export(EXPORT)`:
.. _EXPORT:
.. code-block:: cmake
export(EXPORT <export-name> [NAMESPACE <namespace>] [FILE <filename>]
[CXX_MODULES_DIRECTORY <directory>])
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 `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.
Exporting Packages
^^^^^^^^^^^^^^^^^^
.. _`export(PACKAGE)`:
.. _PACKAGE:
.. code-block:: cmake
export(PACKAGE <PackageName>)
@ -64,23 +138,13 @@ build tree. In some cases, for example for packaging and for system
wide installations, it is not desirable to write the user package
registry.
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.
.. versionchanged:: 3.1
If the :variable:`CMAKE_EXPORT_NO_PACKAGE_REGISTRY` variable
is enabled, the ``export(PACKAGE)`` command will do nothing.
.. code-block:: cmake
export(TARGETS [target1 [target2 [...]]] [ANDROID_MK <filename>])
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 CMP0022 is NEW for all
targets given. A error will be issued if that policy is set to OLD for one
of the targets.
.. 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.

View File

@ -3,6 +3,21 @@ file
File manipulation command.
This command is dedicated to file and path manipulation requiring access to the
filesystem.
For other path manipulation, handling only syntactic aspects, have a look at
:command:`cmake_path` command.
.. note::
The sub-commands `RELATIVE_PATH`_, `TO_CMAKE_PATH`_ and `TO_NATIVE_PATH`_ has
been superseded, respectively, by sub-commands
:ref:`RELATIVE_PATH <cmake_path-RELATIVE_PATH>`,
:ref:`CONVERT ... TO_CMAKE_PATH_LIST <cmake_path-TO_CMAKE_PATH_LIST>` and
:ref:`CONVERT ... TO_NATIVE_PATH_LIST <cmake_path-TO_NATIVE_PATH_LIST>` of
:command:`cmake_path` command.
Synopsis
^^^^^^^^
@ -19,28 +34,37 @@ Synopsis
file({`WRITE`_ | `APPEND`_} <filename> <content>...)
file({`TOUCH`_ | `TOUCH_NOCREATE`_} [<file>...])
file(`GENERATE`_ OUTPUT <output-file> [...])
file(`CONFIGURE`_ OUTPUT <output-file> CONTENT <content> [...])
`Filesystem`_
file({`GLOB`_ | `GLOB_RECURSE`_} <out-var> [...] [<globbing-expr>...])
file(`RENAME`_ <oldname> <newname>)
file({`REMOVE`_ | `REMOVE_RECURSE`_ } [<files>...])
file(`MAKE_DIRECTORY`_ [<dir>...])
file({`REMOVE`_ | `REMOVE_RECURSE`_ } [<files>...])
file(`RENAME`_ <oldname> <newname> [...])
file(`COPY_FILE`_ <oldname> <newname> [...])
file({`COPY`_ | `INSTALL`_} <file>... DESTINATION <dir> [...])
file(`SIZE`_ <filename> <out-var>)
file(`READ_SYMLINK`_ <linkname> <out-var>)
file(`CREATE_LINK`_ <original> <linkname> [...])
file(`CHMOD`_ <files>... <directories>... PERMISSIONS <permissions>... [...])
file(`CHMOD_RECURSE`_ <files>... <directories>... PERMISSIONS <permissions>... [...])
`Path Conversion`_
file(`REAL_PATH`_ <path> <out-var> [BASE_DIRECTORY <dir>] [EXPAND_TILDE])
file(`RELATIVE_PATH`_ <out-var> <directory> <file>)
file({`TO_CMAKE_PATH`_ | `TO_NATIVE_PATH`_} <path> <out-var>)
`Transfer`_
file(`DOWNLOAD`_ <url> <file> [...])
file(`DOWNLOAD`_ <url> [<file>] [...])
file(`UPLOAD`_ <file> <url> [...])
`Locking`_
file(`LOCK`_ <path> [...])
`Archiving`_
file(`ARCHIVE_CREATE`_ OUTPUT <archive> PATHS <paths>... [...])
file(`ARCHIVE_EXTRACT`_ INPUT <archive> [...])
Reading
^^^^^^^
@ -54,7 +78,9 @@ Reading
Read content from a file called ``<filename>`` and store it in a
``<variable>``. Optionally start from the given ``<offset>`` and
read at most ``<max-in>`` bytes. The ``HEX`` option causes data to
be converted to a hexadecimal representation (useful for binary data).
be converted to a hexadecimal representation (useful for binary data). If the
``HEX`` option is specified, letters in the output (``a`` through ``f``) are in
lowercase.
.. _STRINGS:
@ -90,13 +116,19 @@ Parse a list of ASCII strings from ``<filename>`` and store it in
binary while reading unless this option is given.
``REGEX <regex>``
Consider only strings that match the given regular expression.
Consider only strings that match the given regular expression,
as described under :ref:`string(REGEX) <Regex Specification>`.
``ENCODING <encoding-type>``
.. versionadded:: 3.1
Consider strings of a given encoding. Currently supported encodings are:
UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. If the ENCODING option
is not provided and the file has a Byte Order Mark, the ENCODING option
will be defaulted to respect the Byte Order Mark.
``UTF-8``, ``UTF-16LE``, ``UTF-16BE``, ``UTF-32LE``, ``UTF-32BE``.
If the ``ENCODING`` option is not provided and the file has a Byte Order Mark,
the ``ENCODING`` option will be defaulted to respect the Byte Order Mark.
.. versionadded:: 3.2
Added the ``UTF-16LE``, ``UTF-16BE``, ``UTF-32LE``, ``UTF-32BE`` encodings.
For example, the code
@ -148,13 +180,19 @@ the ``<format>`` and ``UTC`` options.
[PRE_EXCLUDE_REGEXES [<regexes>...]]
[POST_INCLUDE_REGEXES [<regexes>...]]
[POST_EXCLUDE_REGEXES [<regexes>...]]
[POST_INCLUDE_FILES [<files>...]]
[POST_EXCLUDE_FILES [<files>...]]
)
.. versionadded:: 3.16
Recursively get the list of libraries depended on by the given files.
Please note that this sub-command is not intended to be used in project mode.
Instead, use it in an :command:`install(CODE)` or :command:`install(SCRIPT)`
block. For example:
It is intended for use at install time, either from code generated by the
:command:`install(RUNTIME_DEPENDENCY_SET)` command, or from code provided by
the project via :command:`install(CODE)` or :command:`install(SCRIPT)`.
For example:
.. code-block:: cmake
@ -243,8 +281,20 @@ be resolved. See below for a full description of how they work.
List of post-exclude regexes through which to filter the names of resolved
dependencies.
These arguments can be used to blacklist unwanted system libraries when
resolving the dependencies, or to whitelist libraries from a specific
``POST_INCLUDE_FILES <files>``
.. versionadded:: 3.21
List of post-include filenames through which to filter the names of resolved
dependencies. Symlinks are resolved when attempting to match these filenames.
``POST_EXCLUDE_FILES <files>``
.. versionadded:: 3.21
List of post-exclude filenames through which to filter the names of resolved
dependencies. Symlinks are resolved when attempting to match these filenames.
These arguments can be used to exclude unwanted system libraries when
resolving the dependencies, or to include libraries from a specific
directory. The filtering works as follows:
1. If the not-yet-resolved dependency matches any of the
@ -256,16 +306,18 @@ directory. The filtering works as follows:
4. ``file(GET_RUNTIME_DEPENDENCIES)`` searches for the dependency according to
the linking rules of the platform (see below).
5. If the dependency is found, and its full path matches one of the
``POST_INCLUDE_REGEXES``, the full path is added to the resolved
dependencies, and ``file(GET_RUNTIME_DEPENDENCIES)`` recursively resolves
that library's own dependencies. Otherwise, resolution proceeds to step 6.
6. If the dependency is found, but its full path matches one of the
``POST_EXCLUDE_REGEXES``, it is not added to the resolved dependencies, and
dependency resolution stops for that dependency.
7. If the dependency is found, and its full path does not match either
``POST_INCLUDE_REGEXES`` or ``POST_EXCLUDE_REGEXES``, the full path is added
``POST_INCLUDE_REGEXES`` or ``POST_INCLUDE_FILES``, the full path is added
to the resolved dependencies, and ``file(GET_RUNTIME_DEPENDENCIES)``
recursively resolves that library's own dependencies.
recursively resolves that library's own dependencies. Otherwise, resolution
proceeds to step 6.
6. If the dependency is found, but its full path matches one of the
``POST_EXCLUDE_REGEXES`` or ``POST_EXCLUDE_FILES``, it is not added to the
resolved dependencies, and dependency resolution stops for that dependency.
7. If the dependency is found, and its full path does not match either
``POST_INCLUDE_REGEXES``, ``POST_INCLUDE_FILES``, ``POST_EXCLUDE_REGEXES``,
or ``POST_EXCLUDE_FILES``, the full path is added to the resolved
dependencies, and ``file(GET_RUNTIME_DEPENDENCIES)`` recursively resolves
that library's own dependencies.
Different platforms have different rules for how dependencies are resolved.
These specifics are described here.
@ -395,8 +447,11 @@ dependency resolution:
Determines the path to the tool to use for dependency resolution. This is the
actual path to ``objdump``, ``dumpbin``, or ``otool``.
If this variable is not specified, it is determined automatically by system
introspection.
If this variable is not specified, it is determined by the value of
``CMAKE_OBJDUMP`` if set, else by system introspection.
.. versionadded:: 3.18
Use ``CMAKE_OBJDUMP`` if set.
Writing
^^^^^^^
@ -426,6 +481,8 @@ to update the file only when its content changes.
file(TOUCH [<files>...])
file(TOUCH_NOCREATE [<files>...])
.. versionadded:: 3.12
Create a file with no content if it does not yet exist. If the file already
exists, its access and/or modification will be updated to the time when the
function call is executed.
@ -442,7 +499,10 @@ modified.
file(GENERATE OUTPUT output-file
<INPUT input-file|CONTENT content>
[CONDITION expression])
[CONDITION expression] [TARGET target]
[NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS |
FILE_PERMISSIONS <permissions>...]
[NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
Generate an output file for each build configuration supported by the current
:manual:`CMake Generator <cmake-generators(7)>`. Evaluate
@ -459,8 +519,10 @@ from the input content to produce the output content. The options are:
``INPUT <input-file>``
Use the content from a given file as input.
A relative path is treated with respect to the value of
:variable:`CMAKE_CURRENT_SOURCE_DIR`. See policy :policy:`CMP0070`.
.. versionchanged:: 3.10
A relative path is treated with respect to the value of
:variable:`CMAKE_CURRENT_SOURCE_DIR`. See policy :policy:`CMP0070`.
``OUTPUT <output-file>``
Specify the output file name to generate. Use generator expressions
@ -468,9 +530,46 @@ from the input content to produce the output content. The options are:
name. Multiple configurations may generate the same output file only
if the generated content is identical. Otherwise, the ``<output-file>``
must evaluate to an unique name for each configuration.
A relative path (after evaluating generator expressions) is treated
with respect to the value of :variable:`CMAKE_CURRENT_BINARY_DIR`.
See policy :policy:`CMP0070`.
.. versionchanged:: 3.10
A relative path (after evaluating generator expressions) is treated
with respect to the value of :variable:`CMAKE_CURRENT_BINARY_DIR`.
See policy :policy:`CMP0070`.
``TARGET <target>``
.. versionadded:: 3.19
Specify which target to use when evaluating generator expressions that
require a target for evaluation (e.g. ``$<COMPILE_FEATURES:...>``,
``$<TARGET_PROPERTY:prop>``).
``NO_SOURCE_PERMISSIONS``
.. versionadded:: 3.20
The generated file permissions default to the standard 644 value
(-rw-r--r--).
``USE_SOURCE_PERMISSIONS``
.. versionadded:: 3.20
Transfer the file permissions of the ``INPUT`` file to the generated 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.
It is an error to specify this option without ``INPUT``.
``FILE_PERMISSIONS <permissions>...``
.. versionadded:: 3.20
Use the specified permissions for the generated file.
``NEWLINE_STYLE <style>``
.. versionadded:: 3.20
Specify the newline style for the generated file. Specify
``UNIX`` or ``LF`` for ``\n`` newlines, or specify
``DOS``, ``WIN32``, or ``CRLF`` for ``\r\n`` newlines.
Exactly one ``CONTENT`` or ``INPUT`` option must be given. A specific
``OUTPUT`` file may be named by at most one invocation of ``file(GENERATE)``.
@ -482,6 +581,46 @@ generation phase. The output file will not yet have been written when the
``file(GENERATE)`` command returns, it is written only after processing all
of a project's ``CMakeLists.txt`` files.
.. _CONFIGURE:
.. code-block:: cmake
file(CONFIGURE OUTPUT output-file
CONTENT content
[ESCAPE_QUOTES] [@ONLY]
[NEWLINE_STYLE [UNIX|DOS|WIN32|LF|CRLF] ])
.. versionadded:: 3.18
Generate an output file using the input given by ``CONTENT`` and substitute
variable values referenced as ``@VAR@`` or ``${VAR}`` contained therein. The
substitution rules behave the same as the :command:`configure_file` command.
In order to match :command:`configure_file`'s behavior, generator expressions
are not supported for both ``OUTPUT`` and ``CONTENT``.
The arguments are:
``OUTPUT <output-file>``
Specify the output file name to generate. A relative path is treated with
respect to the value of :variable:`CMAKE_CURRENT_BINARY_DIR`.
``<output-file>`` does not support generator expressions.
``CONTENT <content>``
Use the content given explicitly as input.
``<content>`` does not support generator expressions.
``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.
Filesystem
^^^^^^^^^^
@ -501,20 +640,25 @@ Generate a list of files that match the ``<globbing-expressions>`` and
store it into the ``<variable>``. Globbing expressions are similar to
regular expressions, but much simpler. If ``RELATIVE`` flag is
specified, the results will be returned as relative paths to the given
path. The results will be ordered lexicographically.
path.
.. versionchanged:: 3.6
The results will be ordered lexicographically.
On Windows and macOS, globbing is case-insensitive even if the underlying
filesystem is case-sensitive (both filenames and globbing expressions are
converted to lowercase before matching). On other platforms, globbing is
case-sensitive.
If the ``CONFIGURE_DEPENDS`` flag is specified, CMake will add logic
to the main build system check target to rerun the flagged ``GLOB`` commands
at build time. If any of the outputs change, CMake will regenerate the build
system.
.. versionadded:: 3.3
By default ``GLOB`` lists directories - directories are omitted in result if
``LIST_DIRECTORIES`` is set to false.
By default ``GLOB`` lists directories - directories are omitted in result if
``LIST_DIRECTORIES`` is set to false.
.. versionadded:: 3.12
If the ``CONFIGURE_DEPENDS`` flag is specified, CMake will add logic
to the main build system check target to rerun the flagged ``GLOB`` commands
at build time. If any of the outputs change, CMake will regenerate the build
system.
.. note::
We do not recommend using GLOB to collect a list of source files from
@ -537,23 +681,23 @@ matched directory and match the files. Subdirectories that are symlinks
are only traversed if ``FOLLOW_SYMLINKS`` is given or policy
:policy:`CMP0009` is not set to ``NEW``.
By default ``GLOB_RECURSE`` omits directories from result list - setting
``LIST_DIRECTORIES`` to true adds directories to result list.
If ``FOLLOW_SYMLINKS`` is given or policy :policy:`CMP0009` is not set to
``OLD`` then ``LIST_DIRECTORIES`` treats symlinks as directories.
.. versionadded:: 3.3
By default ``GLOB_RECURSE`` omits directories from result list - setting
``LIST_DIRECTORIES`` to true adds directories to result list.
If ``FOLLOW_SYMLINKS`` is given or policy :policy:`CMP0009` is not set to
``NEW`` then ``LIST_DIRECTORIES`` treats symlinks as directories.
Examples of recursive globbing include::
/dir/*.py - match all python files in /dir and subdirectories
.. _RENAME:
.. _MAKE_DIRECTORY:
.. code-block:: cmake
file(RENAME <oldname> <newname>)
file(MAKE_DIRECTORY [<directories>...])
Move a file or directory within a filesystem from ``<oldname>`` to
``<newname>``, replacing the destination atomically.
Create the given directories and their parents as needed.
.. _REMOVE:
.. _REMOVE_RECURSE:
@ -566,15 +710,71 @@ Move a file or directory within a filesystem from ``<oldname>`` to
Remove the given files. The ``REMOVE_RECURSE`` mode will remove the given
files and directories, also non-empty directories. No error is emitted if a
given file does not exist. Relative input paths are evaluated with respect
to the current source directory. Empty input paths are ignored with a warning.
to the current source directory.
.. _MAKE_DIRECTORY:
.. versionchanged:: 3.15
Empty input paths are ignored with a warning. Previous versions of CMake
interpreted empty strings as a relative path with respect to the current
directory and removed its contents.
.. _RENAME:
.. code-block:: cmake
file(MAKE_DIRECTORY [<directories>...])
file(RENAME <oldname> <newname>
[RESULT <result>]
[NO_REPLACE])
Create the given directories and their parents as needed.
Move a file or directory within a filesystem from ``<oldname>`` to
``<newname>``, replacing the destination atomically.
The options are:
``RESULT <result>``
.. versionadded:: 3.21
Set ``<result>`` variable to ``0`` on success or an error message otherwise.
If ``RESULT`` is not specified and the operation fails, an error is emitted.
``NO_REPLACE``
.. versionadded:: 3.21
If the ``<newname>`` path already exists, do not replace it.
If ``RESULT <result>`` is used, the result variable will be
set to ``NO_REPLACE``. Otherwise, an error is emitted.
.. _COPY_FILE:
.. code-block:: cmake
file(COPY_FILE <oldname> <newname>
[RESULT <result>]
[ONLY_IF_DIFFERENT])
.. versionadded:: 3.21
Copy a file from ``<oldname>`` to ``<newname>``. Directories are not
supported. Symlinks are ignored and ``<oldfile>``'s content is read and
written to ``<newname>`` as a new file.
The options are:
``RESULT <result>``
Set ``<result>`` variable to ``0`` on success or an error message otherwise.
If ``RESULT`` is not specified and the operation fails, an error is emitted.
``ONLY_IF_DIFFERENT``
If the ``<newname>`` path already exists, do not replace it if the file's
contents are already the same as ``<oldname>`` (this avoids updating
``<newname>``'s timestamp).
This sub-command has some similarities to :command:`configure_file` with the
``COPYONLY`` option. An important difference is that :command:`configure_file`
creates a dependency on the source file, so CMake will be re-run if it changes.
The ``file(COPY_FILE)`` sub-command does not create such a dependency.
See also the ``file(COPY)`` sub-command just below which provides
further file-copying capabilities.
.. _COPY:
.. _INSTALL:
@ -582,14 +782,19 @@ Create the given directories and their parents as needed.
.. code-block:: cmake
file(<COPY|INSTALL> <files>... DESTINATION <dir>
[NO_SOURCE_PERMISSIONS | USE_SOURCE_PERMISSIONS]
[FILE_PERMISSIONS <permissions>...]
[DIRECTORY_PERMISSIONS <permissions>...]
[NO_SOURCE_PERMISSIONS] [USE_SOURCE_PERMISSIONS]
[FOLLOW_SYMLINK_CHAIN]
[FILES_MATCHING]
[[PATTERN <pattern> | REGEX <regex>]
[EXCLUDE] [PERMISSIONS <permissions>...]] [...])
.. note::
For a simple file copying operation, the ``file(COPY_FILE)`` sub-command
just above may be easier to use.
The ``COPY`` signature copies files, directories, and symlinks to a
destination folder. Relative input paths are evaluated with respect
to the current source directory, and a relative destination is
@ -599,17 +804,18 @@ at the destination with the same timestamp. Copying preserves input
permissions unless explicit permissions or ``NO_SOURCE_PERMISSIONS``
are given (default is ``USE_SOURCE_PERMISSIONS``).
If ``FOLLOW_SYMLINK_CHAIN`` is specified, ``COPY`` will recursively resolve
the symlinks at the paths given until a real file is found, and install
a corresponding symlink in the destination for each symlink encountered. For
each symlink that is installed, the resolution is stripped of the directory,
leaving only the filename, meaning that the new symlink points to a file in
the same directory as the symlink. This feature is useful on some Unix systems,
where libraries are installed as a chain of symlinks with version numbers, with
less specific versions pointing to more specific versions.
``FOLLOW_SYMLINK_CHAIN`` will install all of these symlinks and the library
itself into the destination directory. For example, if you have the following
directory structure:
.. versionadded:: 3.15
If ``FOLLOW_SYMLINK_CHAIN`` is specified, ``COPY`` will recursively resolve
the symlinks at the paths given until a real file is found, and install
a corresponding symlink in the destination for each symlink encountered. For
each symlink that is installed, the resolution is stripped of the directory,
leaving only the filename, meaning that the new symlink points to a file in
the same directory as the symlink. This feature is useful on some Unix systems,
where libraries are installed as a chain of symlinks with version numbers, with
less specific versions pointing to more specific versions.
``FOLLOW_SYMLINK_CHAIN`` will install all of these symlinks and the library
itself into the destination directory. For example, if you have the following
directory structure:
* ``/opt/foo/lib/libfoo.so.1.2.3``
* ``/opt/foo/lib/libfoo.so.1.2 -> libfoo.so.1.2.3``
@ -632,17 +838,24 @@ of their content even if options are used to select a subset of
files.
The ``INSTALL`` signature differs slightly from ``COPY``: it prints
status messages (subject to the :variable:`CMAKE_INSTALL_MESSAGE` variable),
and ``NO_SOURCE_PERMISSIONS`` is default.
status messages, and ``NO_SOURCE_PERMISSIONS`` is default.
Installation scripts generated by the :command:`install` command
use this signature (with some undocumented options for internal use).
.. versionchanged:: 3.22
The environment variable :envvar:`CMAKE_INSTALL_MODE` can override the
default copying behavior of :command:`file(INSTALL)`.
.. _SIZE:
.. code-block:: cmake
file(SIZE <filename> <variable>)
.. versionadded:: 3.14
Determine the file size of the ``<filename>`` and put the result in
``<variable>`` variable. Requires that ``<filename>`` is a valid path
pointing to a file and is readable.
@ -653,6 +866,8 @@ pointing to a file and is readable.
file(READ_SYMLINK <linkname> <variable>)
.. versionadded:: 3.14
This subcommand queries the symlink ``<linkname>`` and stores the path it
points to in the result ``<variable>``. If ``<linkname>`` does not exist or
is not a symlink, CMake issues a fatal error.
@ -677,6 +892,8 @@ absolute path is obtained:
file(CREATE_LINK <original> <linkname>
[RESULT <result>] [COPY_ON_ERROR] [SYMBOLIC])
.. versionadded:: 3.14
Create a link ``<linkname>`` that points to ``<original>``.
It will be a hard link by default, but providing the ``SYMBOLIC`` option
results in a symbolic link instead. Hard links require that ``original``
@ -692,9 +909,86 @@ creating the link fails. It can be useful for handling situations such as
``<original>`` and ``<linkname>`` being on different drives or mount points,
which would make them unable to support a hard link.
.. _CHMOD:
.. code-block:: cmake
file(CHMOD <files>... <directories>...
[PERMISSIONS <permissions>...]
[FILE_PERMISSIONS <permissions>...]
[DIRECTORY_PERMISSIONS <permissions>...])
.. versionadded:: 3.19
Set the permissions for the ``<files>...`` and ``<directories>...`` specified.
Valid permissions are ``OWNER_READ``, ``OWNER_WRITE``, ``OWNER_EXECUTE``,
``GROUP_READ``, ``GROUP_WRITE``, ``GROUP_EXECUTE``, ``WORLD_READ``,
``WORLD_WRITE``, ``WORLD_EXECUTE``, ``SETUID``, ``SETGID``.
Valid combination of keywords are:
``PERMISSIONS``
All items are changed.
``FILE_PERMISSIONS``
Only files are changed.
``DIRECTORY_PERMISSIONS``
Only directories are changed.
``PERMISSIONS`` and ``FILE_PERMISSIONS``
``FILE_PERMISSIONS`` overrides ``PERMISSIONS`` for files.
``PERMISSIONS`` and ``DIRECTORY_PERMISSIONS``
``DIRECTORY_PERMISSIONS`` overrides ``PERMISSIONS`` for directories.
``FILE_PERMISSIONS`` and ``DIRECTORY_PERMISSIONS``
Use ``FILE_PERMISSIONS`` for files and ``DIRECTORY_PERMISSIONS`` for
directories.
.. _CHMOD_RECURSE:
.. code-block:: cmake
file(CHMOD_RECURSE <files>... <directories>...
[PERMISSIONS <permissions>...]
[FILE_PERMISSIONS <permissions>...]
[DIRECTORY_PERMISSIONS <permissions>...])
.. versionadded:: 3.19
Same as `CHMOD`_, but change the permissions of files and directories present in
the ``<directories>...`` recursively.
Path Conversion
^^^^^^^^^^^^^^^
.. _REAL_PATH:
.. code-block:: cmake
file(REAL_PATH <path> <out-var> [BASE_DIRECTORY <dir>] [EXPAND_TILDE])
.. versionadded:: 3.19
Compute the absolute path to an existing file or directory with symlinks
resolved.
``BASE_DIRECTORY <dir>``
If the provided ``<path>`` is a relative path, it is evaluated relative to the
given base directory ``<dir>``. If no base directory is provided, the default
base directory will be :variable:`CMAKE_CURRENT_SOURCE_DIR`.
``EXPAND_TILDE``
.. versionadded:: 3.21
If the ``<path>`` is ``~`` or starts with ``~/``, the ``~`` is replaced by
the user's home directory. The path to the home directory is obtained from
environment variables. On Windows, the ``USERPROFILE`` environment variable
is used, falling back to the ``HOME`` environment variable if ``USERPROFILE``
is not defined. On all other platforms, only ``HOME`` is used.
.. _RELATIVE_PATH:
.. code-block:: cmake
@ -718,7 +1012,8 @@ system search path like ``$ENV{PATH}``. A search path will be converted
to a cmake-style list separated by ``;`` characters.
The ``TO_NATIVE_PATH`` mode converts a cmake-style ``<path>`` into a native
path with platform-specific slashes (``\`` on Windows and ``/`` elsewhere).
path with platform-specific slashes (``\`` on Windows hosts and ``/``
elsewhere).
Always use double quotes around the ``<path>`` to be sure it is treated
as a single argument to this command.
@ -731,12 +1026,17 @@ Transfer
.. code-block:: cmake
file(DOWNLOAD <url> <file> [<options>...])
file(DOWNLOAD <url> [<file>] [<options>...])
file(UPLOAD <file> <url> [<options>...])
The ``DOWNLOAD`` mode downloads the given ``<url>`` to a local ``<file>``.
The ``DOWNLOAD`` subcommand downloads the given ``<url>`` to a local ``<file>``.
The ``UPLOAD`` mode uploads a local ``<file>`` to a given ``<url>``.
.. versionadded:: 3.19
If ``<file>`` is not specified for ``file(DOWNLOAD)``, the file is not saved.
This can be useful if you want to know if a file can be downloaded (for example,
to check that it exists) without actually saving it anywhere.
Options to both ``DOWNLOAD`` and ``UPLOAD`` are:
``INACTIVITY_TIMEOUT <seconds>``
@ -760,14 +1060,20 @@ Options to both ``DOWNLOAD`` and ``UPLOAD`` are:
Terminate the operation after a given total time has elapsed.
``USERPWD <username>:<password>``
.. versionadded:: 3.7
Set username and password for operation.
``HTTPHEADER <HTTP-header>``
.. versionadded:: 3.7
HTTP header for operation. Suboption can be repeated several times.
``NETRC <level>``
.. versionadded:: 3.11
Specify whether the .netrc file is to be used for operation. If this
option is not specified, the value of the ``CMAKE_NETRC`` variable
option is not specified, the value of the :variable:`CMAKE_NETRC` variable
will be used instead.
Valid levels are:
@ -782,13 +1088,32 @@ Options to both ``DOWNLOAD`` and ``UPLOAD`` are:
The .netrc file is required, and information in the URL is ignored.
``NETRC_FILE <file>``
.. versionadded:: 3.11
Specify an alternative .netrc file to the one in your home directory,
if the ``NETRC`` level is ``OPTIONAL`` or ``REQUIRED``. If this option
is not specified, the value of the ``CMAKE_NETRC_FILE`` variable will
is not specified, the value of the :variable:`CMAKE_NETRC_FILE` variable will
be used instead.
If neither ``NETRC`` option is given CMake will check variables
``CMAKE_NETRC`` and ``CMAKE_NETRC_FILE``, respectively.
``TLS_VERIFY <ON|OFF>``
Specify whether to verify the server certificate for ``https://`` URLs.
The default is to *not* verify. If this option is not specified, the value
of the :variable:`CMAKE_TLS_VERIFY` variable will be used instead.
.. versionadded:: 3.18
Added support to ``file(UPLOAD)``.
``TLS_CAINFO <file>``
Specify a custom Certificate Authority file for ``https://`` URLs. If this
option is not specified, the value of the :variable:`CMAKE_TLS_CAINFO`
variable will be used instead.
.. versionadded:: 3.18
Added support to ``file(UPLOAD)``.
For ``https://`` URLs CMake must be built with OpenSSL support. ``TLS/SSL``
certificates are not checked by default. Set ``TLS_VERIFY`` to ``ON`` to
check certificates.
Additional options to ``DOWNLOAD`` are:
@ -796,23 +1121,27 @@ Additional options to ``DOWNLOAD`` are:
Verify that the downloaded content hash matches the expected value, where
``ALGO`` is one of the algorithms supported by ``file(<HASH>)``.
If it does not match, the operation fails with an error.
If the file already exists and matches the hash, the download is skipped.
If the file already exists and does not match the hash, the file is
downloaded again. If after download the file does not match the hash, the
operation fails with an error. It is an error to specify this option if
``DOWNLOAD`` is not given a ``<file>``.
``EXPECTED_MD5 <value>``
Historical short-hand for ``EXPECTED_HASH MD5=<value>``.
Historical short-hand for ``EXPECTED_HASH MD5=<value>``. It is an error to
specify this if ``DOWNLOAD`` is not given a ``<file>``.
``TLS_VERIFY <ON|OFF>``
Specify whether to verify the server certificate for ``https://`` URLs.
The default is to *not* verify.
``RANGE_START <value>``
.. versionadded:: 3.24
``TLS_CAINFO <file>``
Specify a custom Certificate Authority file for ``https://`` URLs.
Offset of the start of the range in file in bytes. Could be omitted to
download up to the specified ``RANGE_END``.
For ``https://`` URLs CMake must be built with OpenSSL support. ``TLS/SSL``
certificates are not checked by default. Set ``TLS_VERIFY`` to ``ON`` to
check certificates and/or use ``EXPECTED_HASH`` to verify downloaded content.
If neither ``TLS`` option is given CMake will check variables
``CMAKE_TLS_VERIFY`` and ``CMAKE_TLS_CAINFO``, respectively.
``RANGE_END <value>``
.. versionadded:: 3.24
Offset of the end of the range in file in bytes. Could be omitted to
download everything from the specified ``RANGE_START`` to the end of file.
Locking
^^^^^^^
@ -826,6 +1155,8 @@ Locking
[RESULT_VARIABLE <variable>]
[TIMEOUT <seconds>])
.. versionadded:: 3.2
Lock a file specified by ``<path>`` if no ``DIRECTORY`` option present and file
``<path>/cmake.lock`` otherwise. File will be locked for scope defined by
``GUARD`` option (default value is ``PROCESS``). ``RELEASE`` option can be used
@ -846,3 +1177,80 @@ child directory or file.
Trying to lock file twice is not allowed. Any intermediate directories and
file itself will be created if they not exist. ``GUARD`` and ``TIMEOUT``
options ignored on ``RELEASE`` operation.
Archiving
^^^^^^^^^
.. _ARCHIVE_CREATE:
.. code-block:: cmake
file(ARCHIVE_CREATE OUTPUT <archive>
PATHS <paths>...
[FORMAT <format>]
[COMPRESSION <compression> [COMPRESSION_LEVEL <compression-level>]]
[MTIME <mtime>]
[VERBOSE])
.. versionadded:: 3.18
Creates the specified ``<archive>`` file with the files and directories
listed in ``<paths>``. Note that ``<paths>`` must list actual files or
directories, wildcards are not supported.
Use the ``FORMAT`` option to specify the archive format. Supported values
for ``<format>`` are ``7zip``, ``gnutar``, ``pax``, ``paxr``, ``raw`` and
``zip``. If ``FORMAT`` is not given, the default format is ``paxr``.
Some archive formats allow the type of compression to be specified.
The ``7zip`` and ``zip`` archive formats already imply a specific type of
compression. The other formats use no compression by default, but can be
directed to do so with the ``COMPRESSION`` option. Valid values for
``<compression>`` are ``None``, ``BZip2``, ``GZip``, ``XZ``, and ``Zstd``.
.. versionadded:: 3.19
The compression level can be specified with the ``COMPRESSION_LEVEL`` option.
The ``<compression-level>`` should be between 0-9, with the default being 0.
The ``COMPRESSION`` option must be present when ``COMPRESSION_LEVEL`` is given.
.. note::
With ``FORMAT`` set to ``raw`` only one file will be compressed with the
compression type specified by ``COMPRESSION``.
The ``VERBOSE`` option enables verbose output for the archive operation.
To specify the modification time recorded in tarball entries, use
the ``MTIME`` option.
.. _ARCHIVE_EXTRACT:
.. code-block:: cmake
file(ARCHIVE_EXTRACT INPUT <archive>
[DESTINATION <dir>]
[PATTERNS <patterns>...]
[LIST_ONLY]
[VERBOSE]
[TOUCH])
.. versionadded:: 3.18
Extracts or lists the content of the specified ``<archive>``.
The directory where the content of the archive will be extracted to can
be specified using the ``DESTINATION`` option. If the directory does not
exist, it will be created. If ``DESTINATION`` is not given, the current
binary directory will be used.
If required, you may select which files and directories to list or extract
from the archive using the specified ``<patterns>``. Wildcards are supported.
If the ``PATTERNS`` option is not given, the entire archive will be listed or
extracted.
``LIST_ONLY`` will list the files in the archive rather than extract them.
.. versionadded:: 3.24
The ``TOUCH`` option gives extracted files a current local
timestamp instead of extracting file timestamps from the archive.
With ``VERBOSE``, the command will produce verbose output.

View File

@ -8,6 +8,8 @@ find_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|
@ -17,7 +19,8 @@ find_file
.. |CMAKE_XXX_PATH| replace:: :variable:`CMAKE_INCLUDE_PATH`
.. |CMAKE_XXX_MAC_PATH| replace:: :variable:`CMAKE_FRAMEWORK_PATH`
.. |SYSTEM_ENVIRONMENT_PATH_XXX| replace:: The directories in ``PATH`` and ``INCLUDE``.
.. |SYSTEM_ENVIRONMENT_PATH_XXX| replace:: The directories in ``INCLUDE``
and ``PATH``.
.. |SYSTEM_ENVIRONMENT_PATH_WINDOWS_XXX| replace:: On Windows hosts:
``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE`
is set, and |SYSTEM_ENVIRONMENT_PREFIX_PATH_XXX_SUBDIR|.

View File

@ -8,6 +8,8 @@ find_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|
@ -17,7 +19,8 @@ find_library
.. |CMAKE_XXX_PATH| replace:: :variable:`CMAKE_LIBRARY_PATH`
.. |CMAKE_XXX_MAC_PATH| replace:: :variable:`CMAKE_FRAMEWORK_PATH`
.. |SYSTEM_ENVIRONMENT_PATH_XXX| replace:: The directories in ``PATH`` and ``INCLUDE``.
.. |SYSTEM_ENVIRONMENT_PATH_XXX| replace:: The directories in ``LIB``
and ``PATH``.
.. |SYSTEM_ENVIRONMENT_PATH_WINDOWS_XXX| replace:: On Windows hosts:
``<prefix>/lib/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE`
is set, and |SYSTEM_ENVIRONMENT_PREFIX_PATH_XXX_SUBDIR|.

View File

@ -1,93 +1,214 @@
find_package
------------
.. |FIND_XXX| replace:: find_package
.. |FIND_ARGS_XXX| replace:: <PackageName>
.. |FIND_XXX_REGISTRY_VIEW_DEFAULT| replace:: ``TARGET``
.. |CMAKE_FIND_ROOT_PATH_MODE_XXX| replace::
:variable:`CMAKE_FIND_ROOT_PATH_MODE_PACKAGE`
.. only:: html
.. contents::
Find an external project, and load its settings.
.. note:: The :guide:`Using Dependencies Guide` provides a high-level
introduction to this general topic. It provides a broader overview of
where the ``find_package()`` command fits into the bigger picture,
including its relationship to the :module:`FetchContent` module.
The guide is recommended pre-reading before moving on to the details below.
Find a package (usually provided by something external to the project),
and load its package-specific details. Calls to this command can also
be intercepted by :ref:`dependency providers <dependency_providers>`.
Search Modes
^^^^^^^^^^^^
The command has a few modes by which it searches for packages:
**Module mode**
In this mode, CMake searches for a file called ``Find<PackageName>.cmake``,
looking first in the locations listed in the :variable:`CMAKE_MODULE_PATH`,
then among the :ref:`Find Modules` provided by the CMake installation.
If the file is found, it is read and processed by CMake. It is responsible
for finding the package, checking the version, and producing any needed
messages. Some Find modules provide limited or no support for versioning;
check the Find module's documentation.
The ``Find<PackageName>.cmake`` file is not typically provided by the
package itself. Rather, it is normally provided by something external to
the package, such as the operating system, CMake itself, or even the project
from which the ``find_package()`` command was called. Being externally
provided, :ref:`Find Modules` tend to be heuristic in nature and are
susceptible to becoming out-of-date. They typically search for certain
libraries, files and other package artifacts.
Module mode is only supported by the
:ref:`basic command signature <Basic Signature>`.
**Config mode**
In this mode, CMake searches for a file called
``<lowercasePackageName>-config.cmake`` or ``<PackageName>Config.cmake``.
It will also look for ``<lowercasePackageName>-config-version.cmake`` or
``<PackageName>ConfigVersion.cmake`` if version details were specified
(see :ref:`version selection` for an explanation of how these separate
version files are used).
In config mode, the command can be given a list of names to search for
as package names. The locations where CMake searches for the config and
version files is considerably more complicated than for Module mode
(see :ref:`search procedure`).
The config and version files are typically installed as part of the
package, so they tend to be more reliable than Find modules. They usually
contain direct knowledge of the package contents, so no searching or
heuristics are needed within the config or version files themselves.
Config mode is supported by both the :ref:`basic <Basic Signature>` and
:ref:`full <Full Signature>` command signatures.
**FetchContent redirection mode**
.. versionadded:: 3.24
A call to ``find_package()`` can be redirected internally to a package
provided by the :module:`FetchContent` module. To the caller, the behavior
will appear similar to Config mode, except that the search logic is
by-passed and the component information is not used. See
:command:`FetchContent_Declare` and :command:`FetchContent_MakeAvailable`
for further details.
When not redirected to a package provided by :module:`FetchContent`, the
command arguments determine whether Module or Config mode is used. When the
`basic signature`_ is used, the command searches in Module mode first.
If the package is not found, the search falls back to Config mode.
A user may set the :variable:`CMAKE_FIND_PACKAGE_PREFER_CONFIG` variable
to true to reverse the priority and direct CMake to search using Config mode
first before falling back to Module mode. The basic signature can also be
forced to use only Module mode with a ``MODULE`` keyword. If the
`full signature`_ is used, the command only searches in Config mode.
Where possible, user code should generally look for packages using the
`basic signature`_, since that allows the package to be found with any mode.
Project maintainers wishing to provide a config package should understand
the bigger picture, as explained in :ref:`Full Signature` and all subsequent
sections on this page.
.. _`basic signature`:
Basic Signature and Module Mode
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Basic Signature
^^^^^^^^^^^^^^^
.. code-block:: cmake
.. parsed-literal::
find_package(<PackageName> [version] [EXACT] [QUIET] [MODULE]
[REQUIRED] [[COMPONENTS] [components...]]
[OPTIONAL_COMPONENTS components...]
[NO_POLICY_SCOPE])
[REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)]
[GLOBAL]
[NO_POLICY_SCOPE]
[BYPASS_PROVIDER])
Finds and loads settings from an external project. ``<PackageName>_FOUND``
will be set to indicate whether the package was found. When the
package is found package-specific information is provided through
variables and :ref:`Imported Targets` documented by the package itself. The
The basic signature is supported by both Module and Config modes.
The ``MODULE`` keyword implies that only Module mode can be used to find
the package, with no fallback to Config mode.
Regardless of the mode used, a ``<PackageName>_FOUND`` variable will be
set to indicate whether the package was found. When the package is found,
package-specific information may be provided through other variables and
:ref:`Imported Targets` documented by the package itself. 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.
A package-specific list of required components may be listed after the
``COMPONENTS`` option (or after the ``REQUIRED`` option if present).
``COMPONENTS`` keyword. If any of these components are not able to be
satisfied, the package overall is considered to be not found. If the
``REQUIRED`` option is also present, this is treated as a fatal error,
otherwise execution still continues. As a form of shorthand, if the
``REQUIRED`` option is present, the ``COMPONENTS`` keyword can be omitted
and the required components can be listed directly after ``REQUIRED``.
Additional optional components may be listed after
``OPTIONAL_COMPONENTS``. Available components and their influence on
whether a package is considered to be found are defined by the target
package.
``OPTIONAL_COMPONENTS``. If these cannot be satisfied, the package overall
can still be considered found, as long as all required components are
satisfied.
The set of available components and their meaning are defined by the
target package. Formally, it is up to the target package how to
interpret the component information given to it, but it should follow
the expectations stated above. For calls where no components are specified,
there is no single expected behavior and target packages should clearly
define what occurs in such cases. Common arrangements include assuming it
should find all components, no components or some well-defined subset of the
available components.
.. versionadded:: 3.24
The ``REGISTRY_VIEW`` keyword specifies which registry views should be
queried. This keyword is only meaningful on ``Windows`` platforms and will
be ignored on all others. Formally, it is up to the target package how to
interpret the registry view information given to it.
.. versionadded:: 3.24
Specifying the ``GLOBAL`` keyword will promote all imported targets to
a global scope in the importing project. Alternatively, this functionality
can be enabled by setting the :variable:`CMAKE_FIND_PACKAGE_TARGETS_GLOBAL`
variable.
.. _FIND_PACKAGE_VERSION_FORMAT:
The ``[version]`` argument requests a version with which the package found
should be compatible (format is ``major[.minor[.patch[.tweak]]]``). The
``EXACT`` option requests that the version be matched exactly. If no
``[version]`` and/or component list is given to a recursive invocation
should be compatible. There are two possible forms in which it may be
specified:
* A single version with the format ``major[.minor[.patch[.tweak]]]``, where
each component is a numeric value.
* A version range with the format ``versionMin...[<]versionMax`` where
``versionMin`` and ``versionMax`` have the same format and constraints
on components being integers as the single version. By default, both end
points are included. By specifying ``<``, the upper end point will be
excluded. Version ranges are only supported with CMake 3.19 or later.
The ``EXACT`` option requests that the version be matched exactly. This option
is incompatible with the specification of a version range.
If no ``[version]`` and/or component list is given to a recursive invocation
inside a find-module, the corresponding arguments are forwarded
automatically from the outer call (including the ``EXACT`` flag for
``[version]``). Version support is currently provided only on a
package-by-package basis (see the `Version Selection`_ section below).
When a version range is specified but the package is only designed to expect
a single version, the package will ignore the upper end point of the range and
only take the single version at the lower end of the range into account.
See the :command:`cmake_policy` command documentation for discussion
of the ``NO_POLICY_SCOPE`` option.
The command has two modes by which it searches for packages: "Module"
mode and "Config" mode. The above signature selects Module mode.
If no module is found the command falls back to Config mode, described
below. This fall back is disabled if the ``MODULE`` option is given.
.. versionadded:: 3.24
The ``BYPASS_PROVIDER`` keyword is only allowed when ``find_package()`` is
being called by a :ref:`dependency provider <dependency_providers>`.
It can be used by providers to call the built-in ``find_package()``
implementation directly and prevent that call from being re-routed back to
itself. Future versions of CMake may detect attempts to use this keyword
from places other than a dependency provider and halt with a fatal error.
In Module mode, CMake searches for a file called ``Find<PackageName>.cmake``.
The file is first searched in the :variable:`CMAKE_MODULE_PATH`,
then among the :ref:`Find Modules` provided by the CMake installation.
If the file is found, it is read and processed by CMake. It is responsible
for finding the package, checking the version, and producing any needed
messages. Some find-modules provide limited or no support for versioning;
check the module documentation.
.. _`full signature`:
If the ``MODULE`` option is not specfied in the above signature,
CMake first searches for the package using Module mode. Then, if the
package is not found, it searches again using Config mode. A user
may set the variable :variable:`CMAKE_FIND_PACKAGE_PREFER_CONFIG` to
``TRUE`` to direct CMake first search using Config mode before falling
back to Module mode.
Full Signature
^^^^^^^^^^^^^^
Full Signature and Config Mode
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
User code should generally look for packages using the above `basic
signature`_. The remainder of this command documentation specifies the
full command signature and details of the search process. Project
maintainers wishing to provide a package to be found by this command
are encouraged to read on.
The complete Config mode command signature is
.. code-block:: cmake
.. parsed-literal::
find_package(<PackageName> [version] [EXACT] [QUIET]
[REQUIRED] [[COMPONENTS] [components...]]
[OPTIONAL_COMPONENTS components...]
[CONFIG|NO_MODULE]
[GLOBAL]
[NO_POLICY_SCOPE]
[BYPASS_PROVIDER]
[NAMES name1 [name2 ...]]
[CONFIGS config1 [config2 ...]]
[HINTS path1 [path2 ... ]]
[PATHS path1 [path2 ... ]]
[REGISTRY_VIEW (64|32|64_32|32_64|HOST|TARGET|BOTH)]
[PATH_SUFFIXES suffix1 [suffix2 ...]]
[NO_DEFAULT_PATH]
[NO_PACKAGE_ROOT_PATH]
@ -97,6 +218,7 @@ The complete Config mode command signature is
[NO_CMAKE_PACKAGE_REGISTRY]
[NO_CMAKE_BUILDS_PATH] # Deprecated; does nothing.
[NO_CMAKE_SYSTEM_PATH]
[NO_CMAKE_INSTALL_PREFIX]
[NO_CMAKE_SYSTEM_PACKAGE_REGISTRY]
[CMAKE_FIND_ROOT_PATH_BOTH |
ONLY_CMAKE_FIND_ROOT_PATH |
@ -109,22 +231,26 @@ proceeds at once with Config mode search.
Config mode search attempts to locate a configuration file provided by the
package to be found. A cache entry called ``<PackageName>_DIR`` is created to
hold the directory containing the file. By default the command
searches for a package with the name ``<PackageName>``. If the ``NAMES`` option
is given the names following it are used instead of ``<PackageName>``.
hold the directory containing the file. By default, the command searches for
a package with the name ``<PackageName>``. If the ``NAMES`` option is given,
the names following it are used instead of ``<PackageName>``. The names are
also considered when determining whether to redirect the call to a package
provided by :module:`FetchContent`.
The command searches for a file called ``<PackageName>Config.cmake`` or
``<lower-case-package-name>-config.cmake`` for each name specified.
``<lowercasePackageName>-config.cmake`` for each name specified.
A replacement set of possible configuration file names may be given
using the ``CONFIGS`` option. The search procedure is specified below.
Once found, the configuration file is read and processed by CMake.
using the ``CONFIGS`` option. The :ref:`search procedure` is specified below.
Once found, any :ref:`version constraint <version selection>` is checked,
and if satisfied, the configuration file is read and processed by CMake.
Since the file is provided by the package it already knows the
location of package contents. The full path to the configuration file
is stored in the cmake variable ``<PackageName>_CONFIG``.
All configuration files which have been considered by CMake while
searching for an installation of the package with an appropriate
version are stored in the cmake variable ``<PackageName>_CONSIDERED_CONFIGS``,
the associated versions in ``<PackageName>_CONSIDERED_VERSIONS``.
searching for the package with an appropriate version are stored in the
``<PackageName>_CONSIDERED_CONFIGS`` variable, and the associated versions
in the ``<PackageName>_CONSIDERED_VERSIONS`` variable.
If the package configuration file cannot be found CMake will generate
an error describing the problem unless the ``QUIET`` argument is
@ -134,124 +260,65 @@ fatal error is generated and the configure step stops executing. If
configuration file CMake will ignore it and search from scratch.
Package maintainers providing CMake package configuration files are
encouraged to name and install them such that the `Search Procedure`_
encouraged to name and install them such that the :ref:`search procedure`
outlined below will find them without requiring use of additional options.
Version Selection
^^^^^^^^^^^^^^^^^
.. _`search procedure`:
When the ``[version]`` argument is given Config mode will only find a
version of the package that claims compatibility with the requested
version (format is ``major[.minor[.patch[.tweak]]]``). If the ``EXACT``
option is given only a version of the package claiming an exact match
of the requested version may be found. CMake does not establish any
convention for the meaning of version numbers. Package version
numbers are checked by "version" files provided by the packages
themselves. For a candidate package configuration file
``<config-file>.cmake`` the corresponding version file is located next
to it and named either ``<config-file>-version.cmake`` or
``<config-file>Version.cmake``. If no such version file is available
then the configuration file is assumed to not be compatible with any
requested version. A basic version file containing generic version
matching code can be created using the
:module:`CMakePackageConfigHelpers` module. When a version file
is found it is loaded to check the requested version number. The
version file is loaded in a nested scope in which the following
variables have been defined:
Config Mode Search Procedure
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
``PACKAGE_FIND_NAME``
the ``<PackageName>``
``PACKAGE_FIND_VERSION``
full requested version string
``PACKAGE_FIND_VERSION_MAJOR``
major version if requested, else 0
``PACKAGE_FIND_VERSION_MINOR``
minor version if requested, else 0
``PACKAGE_FIND_VERSION_PATCH``
patch version if requested, else 0
``PACKAGE_FIND_VERSION_TWEAK``
tweak version if requested, else 0
``PACKAGE_FIND_VERSION_COUNT``
number of version components, 0 to 4
.. note::
When Config mode is used, this search procedure is applied regardless of
whether the :ref:`full <full signature>` or :ref:`basic <basic signature>`
signature was given.
The version file checks whether it satisfies the requested version and
sets these variables:
``PACKAGE_VERSION``
full provided version string
``PACKAGE_VERSION_EXACT``
true if version is exact match
``PACKAGE_VERSION_COMPATIBLE``
true if version is compatible
``PACKAGE_VERSION_UNSUITABLE``
true if unsuitable as any version
These variables are checked by the ``find_package`` command to determine
whether the configuration file provides an acceptable version. They
are not available after the ``find_package`` call returns. If the version
is acceptable the following variables are set:
``<PackageName>_VERSION``
full provided version string
``<PackageName>_VERSION_MAJOR``
major version if provided, else 0
``<PackageName>_VERSION_MINOR``
minor version if provided, else 0
``<PackageName>_VERSION_PATCH``
patch version if provided, else 0
``<PackageName>_VERSION_TWEAK``
tweak version if provided, else 0
``<PackageName>_VERSION_COUNT``
number of version components, 0 to 4
and the corresponding package configuration file is loaded.
When multiple package configuration files are available whose version files
claim compatibility with the version requested it is unspecified which
one is chosen: unless the variable :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER`
is set no attempt is made to choose a highest or closest version number.
To control the order in which ``find_package`` checks for compatibility use
the two variables :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER` and
:variable:`CMAKE_FIND_PACKAGE_SORT_DIRECTION`.
For instance in order to select the highest version one can set
.. code-block:: cmake
SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
before calling ``find_package``.
Search Procedure
^^^^^^^^^^^^^^^^
.. versionadded:: 3.24
All calls to ``find_package()`` (even in Module mode) first look for a config
package file in the :variable:`CMAKE_FIND_PACKAGE_REDIRECTS_DIR` directory.
The :module:`FetchContent` module, or even the project itself, may write files
to that location to redirect ``find_package()`` calls to content already
provided by the project. If no config package file is found in that location,
the search proceeds with the logic described below.
CMake constructs a set of possible installation prefixes for the
package. Under each prefix several directories are searched for a
configuration file. The tables below show the directories searched.
Each entry is meant for installation trees following Windows (``W``), UNIX
(``U``), or Apple (``A``) conventions::
(``U``), or Apple (``A``) conventions:
<prefix>/ (W)
<prefix>/(cmake|CMake)/ (W)
<prefix>/<name>*/ (W)
<prefix>/<name>*/(cmake|CMake)/ (W)
<prefix>/(lib/<arch>|lib*|share)/cmake/<name>*/ (U)
<prefix>/(lib/<arch>|lib*|share)/<name>*/ (U)
<prefix>/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (U)
<prefix>/<name>*/(lib/<arch>|lib*|share)/cmake/<name>*/ (W/U)
<prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/ (W/U)
<prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/ (W/U)
==================================================================== ==========
Entry Convention
==================================================================== ==========
``<prefix>/`` W
``<prefix>/(cmake|CMake)/`` W
``<prefix>/<name>*/`` W
``<prefix>/<name>*/(cmake|CMake)/`` W
``<prefix>/<name>*/(cmake|CMake)/<name>*/`` [#]_ W
``<prefix>/(lib/<arch>|lib*|share)/cmake/<name>*/`` U
``<prefix>/(lib/<arch>|lib*|share)/<name>*/`` U
``<prefix>/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/`` U
``<prefix>/<name>*/(lib/<arch>|lib*|share)/cmake/<name>*/`` W/U
``<prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/`` W/U
``<prefix>/<name>*/(lib/<arch>|lib*|share)/<name>*/(cmake|CMake)/`` W/U
==================================================================== ==========
.. [#] .. versionadded:: 3.25
On systems supporting macOS :prop_tgt:`FRAMEWORK` and :prop_tgt:`BUNDLE`, the
following directories are searched for Frameworks or Application Bundles
containing a configuration file::
containing a configuration file:
<prefix>/<name>.framework/Resources/ (A)
<prefix>/<name>.framework/Resources/CMake/ (A)
<prefix>/<name>.framework/Versions/*/Resources/ (A)
<prefix>/<name>.framework/Versions/*/Resources/CMake/ (A)
<prefix>/<name>.app/Contents/Resources/ (A)
<prefix>/<name>.app/Contents/Resources/CMake/ (A)
=========================================================== ==========
Entry Convention
=========================================================== ==========
``<prefix>/<name>.framework/Resources/`` A
``<prefix>/<name>.framework/Resources/CMake/`` A
``<prefix>/<name>.framework/Versions/*/Resources/`` A
``<prefix>/<name>.framework/Versions/*/Resources/CMake/`` A
``<prefix>/<name>.app/Contents/Resources/`` A
``<prefix>/<name>.app/Contents/Resources/CMake/`` A
=========================================================== ==========
In all cases the ``<name>`` is treated as case-insensitive and corresponds
to any of the names specified (``<PackageName>`` or names given by ``NAMES``).
@ -269,6 +336,18 @@ that order).
if the :prop_gbl:`FIND_LIBRARY_USE_LIBX32_PATHS` property is set to ``TRUE``.
* The ``lib`` path is always searched.
.. versionchanged:: 3.24
On ``Windows`` platform, it is possible to include registry queries as part
of the directories specified through ``HINTS`` and ``PATHS`` keywords, using
a :ref:`dedicated syntax <Find Using Windows Registry>`. Such specifications
will be ignored on all other platforms.
.. versionadded:: 3.24
``REGISTRY_VIEW`` can be specified to manage ``Windows`` registry queries
specified as part of ``PATHS`` and ``HINTS``.
.. include:: FIND_XXX_REGISTRY_VIEW.txt
If ``PATH_SUFFIXES`` is specified, the suffixes are appended to each
(``W``) or (``U``) directory entry one-by-one.
@ -288,37 +367,38 @@ The set of installation prefixes is constructed using the following
steps. If ``NO_DEFAULT_PATH`` is specified all ``NO_*`` options are
enabled.
1. Search paths specified in the :variable:`<PackageName>_ROOT` CMake
variable and the :envvar:`<PackageName>_ROOT` environment variable,
where ``<PackageName>`` is the package to be found.
The package root variables are maintained as a stack so if
called from within a find module, root paths from the parent's find
module will also be searched after paths for the current package.
This can be skipped if ``NO_PACKAGE_ROOT_PATH`` is passed or by setting
the :variable:`CMAKE_FIND_USE_PACKAGE_ROOT_PATH` to ``FALSE``.
See policy :policy:`CMP0074`.
1. .. versionadded:: 3.12
Search paths specified in the :variable:`<PackageName>_ROOT` CMake
variable and the :envvar:`<PackageName>_ROOT` environment variable,
where ``<PackageName>`` is the package to be found.
The package root variables are maintained as a stack so if
called from within a find module, root paths from the parent's find
module will also be searched after paths for the current package.
This can be skipped if ``NO_PACKAGE_ROOT_PATH`` is passed or by setting
the :variable:`CMAKE_FIND_USE_PACKAGE_ROOT_PATH` to ``FALSE``.
See policy :policy:`CMP0074`.
2. Search paths specified in cmake-specific cache variables. These
are intended to be used on the command line with a ``-DVAR=value``.
are intended to be used on the command line with a :option:`-DVAR=VALUE <cmake -D>`.
The values are interpreted as :ref:`semicolon-separated lists <CMake Language Lists>`.
This can be skipped if ``NO_CMAKE_PATH`` is passed or by setting the
:variable:`CMAKE_FIND_USE_CMAKE_PATH` to ``FALSE``::
:variable:`CMAKE_FIND_USE_CMAKE_PATH` to ``FALSE``:
CMAKE_PREFIX_PATH
CMAKE_FRAMEWORK_PATH
CMAKE_APPBUNDLE_PATH
* :variable:`CMAKE_PREFIX_PATH`
* :variable:`CMAKE_FRAMEWORK_PATH`
* :variable:`CMAKE_APPBUNDLE_PATH`
3. Search paths specified in cmake-specific environment variables.
These are intended to be set in the user's shell configuration,
and therefore use the host's native path separator
(``;`` on Windows and ``:`` on UNIX).
This can be skipped if ``NO_CMAKE_ENVIRONMENT_PATH`` is passed or by setting
the :variable:`CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH` to ``FALSE``::
the :variable:`CMAKE_FIND_USE_CMAKE_ENVIRONMENT_PATH` to ``FALSE``:
<PackageName>_DIR
CMAKE_PREFIX_PATH
CMAKE_FRAMEWORK_PATH
CMAKE_APPBUNDLE_PATH
* ``<PackageName>_DIR``
* :envvar:`CMAKE_PREFIX_PATH`
* ``CMAKE_FRAMEWORK_PATH``
* ``CMAKE_APPBUNDLE_PATH``
4. Search paths specified by the ``HINTS`` option. These should be paths
computed by system introspection, such as a hint provided by the
@ -329,9 +409,9 @@ enabled.
skipped if ``NO_SYSTEM_ENVIRONMENT_PATH`` is passed or by setting the
:variable:`CMAKE_FIND_USE_SYSTEM_ENVIRONMENT_PATH` to ``FALSE``. Path entries
ending in ``/bin`` or ``/sbin`` are automatically converted to their
parent directories::
parent directories:
PATH
* ``PATH``
6. Search paths stored in the CMake :ref:`User Package Registry`.
This can be skipped if ``NO_CMAKE_PACKAGE_REGISTRY`` is passed or by
@ -343,13 +423,20 @@ enabled.
package registry.
7. Search cmake variables defined in the Platform files for the
current system. This can be skipped if ``NO_CMAKE_SYSTEM_PATH`` is
passed or by setting the :variable:`CMAKE_FIND_USE_CMAKE_SYSTEM_PATH`
to ``FALSE``::
current system. The searching of :variable:`CMAKE_INSTALL_PREFIX` and
:variable:`CMAKE_STAGING_PREFIX` can be
skipped if ``NO_CMAKE_INSTALL_PREFIX`` is passed or by setting the
:variable:`CMAKE_FIND_USE_INSTALL_PREFIX` to ``FALSE``. All these locations
can be skipped if ``NO_CMAKE_SYSTEM_PATH`` is passed or by setting the
:variable:`CMAKE_FIND_USE_CMAKE_SYSTEM_PATH` to ``FALSE``:
CMAKE_SYSTEM_PREFIX_PATH
CMAKE_SYSTEM_FRAMEWORK_PATH
CMAKE_SYSTEM_APPBUNDLE_PATH
* :variable:`CMAKE_SYSTEM_PREFIX_PATH`
* :variable:`CMAKE_SYSTEM_FRAMEWORK_PATH`
* :variable:`CMAKE_SYSTEM_APPBUNDLE_PATH`
The platform paths that these variables contain are locations that
typically include installed software. An example being ``/usr/local`` for
UNIX based platforms.
8. Search paths stored in the CMake :ref:`System Package Registry`.
This can be skipped if ``NO_CMAKE_SYSTEM_PACKAGE_REGISTRY`` is passed
@ -363,10 +450,14 @@ enabled.
9. Search paths specified by the ``PATHS`` option. These are typically
hard-coded guesses.
.. |FIND_XXX| replace:: find_package
.. |FIND_ARGS_XXX| replace:: <PackageName>
.. |CMAKE_FIND_ROOT_PATH_MODE_XXX| replace::
:variable:`CMAKE_FIND_ROOT_PATH_MODE_PACKAGE`
The :variable:`CMAKE_IGNORE_PATH`, :variable:`CMAKE_IGNORE_PREFIX_PATH`,
:variable:`CMAKE_SYSTEM_IGNORE_PATH` and
:variable:`CMAKE_SYSTEM_IGNORE_PREFIX_PATH` variables can also cause some
of the above locations to be ignored.
.. versionadded:: 3.16
Added the ``CMAKE_FIND_USE_<CATEGORY>`` variables to globally disable
various search locations.
.. include:: FIND_XXX_ROOT.txt
.. include:: FIND_XXX_ORDER.txt
@ -376,8 +467,155 @@ which the file is found. The :variable:`CMAKE_FIND_PACKAGE_RESOLVE_SYMLINKS`
variable may be set to ``TRUE`` before calling ``find_package`` in order
to resolve symbolic links and store the real path to the file.
Every non-REQUIRED ``find_package`` call can be disabled by setting the
:variable:`CMAKE_DISABLE_FIND_PACKAGE_<PackageName>` variable to ``TRUE``.
Every non-REQUIRED ``find_package`` call can be disabled or made REQUIRED:
* Setting the :variable:`CMAKE_DISABLE_FIND_PACKAGE_<PackageName>` variable
to ``TRUE`` disables the package. This also disables redirection to a
package provided by :module:`FetchContent`.
* Setting the :variable:`CMAKE_REQUIRE_FIND_PACKAGE_<PackageName>` variable
to ``TRUE`` makes the package REQUIRED.
Setting both variables to ``TRUE`` simultaneously is an error.
.. _`version selection`:
Config Mode Version Selection
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. note::
When Config mode is used, this version selection process is applied
regardless of whether the :ref:`full <full signature>` or
:ref:`basic <basic signature>` signature was given.
When the ``[version]`` argument is given, Config mode will only find a
version of the package that claims compatibility with the requested
version (see :ref:`format specification <FIND_PACKAGE_VERSION_FORMAT>`). If the
``EXACT`` option is given, only a version of the package claiming an exact match
of the requested version may be found. CMake does not establish any
convention for the meaning of version numbers. Package version
numbers are checked by "version" files provided by the packages themselves
or by :module:`FetchContent`. For a candidate package configuration file
``<config-file>.cmake`` the corresponding version file is located next
to it and named either ``<config-file>-version.cmake`` or
``<config-file>Version.cmake``. If no such version file is available
then the configuration file is assumed to not be compatible with any
requested version. A basic version file containing generic version
matching code can be created using the
:module:`CMakePackageConfigHelpers` module. When a version file
is found it is loaded to check the requested version number. The
version file is loaded in a nested scope in which the following
variables have been defined:
``PACKAGE_FIND_NAME``
The ``<PackageName>``
``PACKAGE_FIND_VERSION``
Full requested version string
``PACKAGE_FIND_VERSION_MAJOR``
Major version if requested, else 0
``PACKAGE_FIND_VERSION_MINOR``
Minor version if requested, else 0
``PACKAGE_FIND_VERSION_PATCH``
Patch version if requested, else 0
``PACKAGE_FIND_VERSION_TWEAK``
Tweak version if requested, else 0
``PACKAGE_FIND_VERSION_COUNT``
Number of version components, 0 to 4
When a version range is specified, the above version variables will hold
values based on the lower end of the version range. This is to preserve
compatibility with packages that have not been implemented to expect version
ranges. In addition, the version range will be described by the following
variables:
``PACKAGE_FIND_VERSION_RANGE``
Full requested version range string
``PACKAGE_FIND_VERSION_RANGE_MIN``
This specifies whether the lower end point of the version range should be
included or excluded. Currently, the only supported value for this variable
is ``INCLUDE``.
``PACKAGE_FIND_VERSION_RANGE_MAX``
This specifies whether the upper end point of the version range should be
included or excluded. The supported values for this variable are
``INCLUDE`` and ``EXCLUDE``.
``PACKAGE_FIND_VERSION_MIN``
Full requested version string of the lower end point of the range
``PACKAGE_FIND_VERSION_MIN_MAJOR``
Major version of the lower end point if requested, else 0
``PACKAGE_FIND_VERSION_MIN_MINOR``
Minor version of the lower end point if requested, else 0
``PACKAGE_FIND_VERSION_MIN_PATCH``
Patch version of the lower end point if requested, else 0
``PACKAGE_FIND_VERSION_MIN_TWEAK``
Tweak version of the lower end point if requested, else 0
``PACKAGE_FIND_VERSION_MIN_COUNT``
Number of version components of the lower end point, 0 to 4
``PACKAGE_FIND_VERSION_MAX``
Full requested version string of the upper end point of the range
``PACKAGE_FIND_VERSION_MAX_MAJOR``
Major version of the upper end point if requested, else 0
``PACKAGE_FIND_VERSION_MAX_MINOR``
Minor version of the upper end point if requested, else 0
``PACKAGE_FIND_VERSION_MAX_PATCH``
Patch version of the upper end point if requested, else 0
``PACKAGE_FIND_VERSION_MAX_TWEAK``
Tweak version of the upper end point if requested, else 0
``PACKAGE_FIND_VERSION_MAX_COUNT``
Number of version components of the upper end point, 0 to 4
Regardless of whether a single version or a version range is specified, the
variable ``PACKAGE_FIND_VERSION_COMPLETE`` will be defined and will hold
the full requested version string as specified.
The version file checks whether it satisfies the requested version and
sets these variables:
``PACKAGE_VERSION``
Full provided version string
``PACKAGE_VERSION_EXACT``
True if version is exact match
``PACKAGE_VERSION_COMPATIBLE``
True if version is compatible
``PACKAGE_VERSION_UNSUITABLE``
True if unsuitable as any version
These variables are checked by the ``find_package`` command to determine
whether the configuration file provides an acceptable version. They
are not available after the ``find_package`` call returns. If the version
is acceptable the following variables are set:
``<PackageName>_VERSION``
Full provided version string
``<PackageName>_VERSION_MAJOR``
Major version if provided, else 0
``<PackageName>_VERSION_MINOR``
Minor version if provided, else 0
``<PackageName>_VERSION_PATCH``
Patch version if provided, else 0
``<PackageName>_VERSION_TWEAK``
Tweak version if provided, else 0
``<PackageName>_VERSION_COUNT``
Number of version components, 0 to 4
and the corresponding package configuration file is loaded.
When multiple package configuration files are available whose version files
claim compatibility with the version requested it is unspecified which
one is chosen: unless the variable :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER`
is set no attempt is made to choose a highest or closest version number.
To control the order in which ``find_package`` checks for compatibility use
the two variables :variable:`CMAKE_FIND_PACKAGE_SORT_ORDER` and
:variable:`CMAKE_FIND_PACKAGE_SORT_DIRECTION`.
For instance in order to select the highest version one can set
.. code-block:: cmake
SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
before calling ``find_package``.
Package File Interface Variables
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@ -387,31 +625,79 @@ defines variables to provide information about the call arguments (and
restores their original state before returning):
``CMAKE_FIND_PACKAGE_NAME``
the ``<PackageName>`` which is searched for
The ``<PackageName>`` which is searched for
``<PackageName>_FIND_REQUIRED``
true if ``REQUIRED`` option was given
True if ``REQUIRED`` option was given
``<PackageName>_FIND_QUIETLY``
true if ``QUIET`` option was given
True if ``QUIET`` option was given
``<PackageName>_FIND_REGISTRY_VIEW``
The requested view if ``REGISTRY_VIEW`` option was given
``<PackageName>_FIND_VERSION``
full requested version string
Full requested version string
``<PackageName>_FIND_VERSION_MAJOR``
major version if requested, else 0
Major version if requested, else 0
``<PackageName>_FIND_VERSION_MINOR``
minor version if requested, else 0
Minor version if requested, else 0
``<PackageName>_FIND_VERSION_PATCH``
patch version if requested, else 0
Patch version if requested, else 0
``<PackageName>_FIND_VERSION_TWEAK``
tweak version if requested, else 0
Tweak version if requested, else 0
``<PackageName>_FIND_VERSION_COUNT``
number of version components, 0 to 4
Number of version components, 0 to 4
``<PackageName>_FIND_VERSION_EXACT``
true if ``EXACT`` option was given
True if ``EXACT`` option was given
``<PackageName>_FIND_COMPONENTS``
list of requested components
List of specified components (required and optional)
``<PackageName>_FIND_REQUIRED_<c>``
true if component ``<c>`` is required,
True if component ``<c>`` is required,
false if component ``<c>`` is optional
When a version range is specified, the above version variables will hold
values based on the lower end of the version range. This is to preserve
compatibility with packages that have not been implemented to expect version
ranges. In addition, the version range will be described by the following
variables:
``<PackageName>_FIND_VERSION_RANGE``
Full requested version range string
``<PackageName>_FIND_VERSION_RANGE_MIN``
This specifies whether the lower end point of the version range is
included or excluded. Currently, ``INCLUDE`` is the only supported value.
``<PackageName>_FIND_VERSION_RANGE_MAX``
This specifies whether the upper end point of the version range is
included or excluded. The possible values for this variable are
``INCLUDE`` or ``EXCLUDE``.
``<PackageName>_FIND_VERSION_MIN``
Full requested version string of the lower end point of the range
``<PackageName>_FIND_VERSION_MIN_MAJOR``
Major version of the lower end point if requested, else 0
``<PackageName>_FIND_VERSION_MIN_MINOR``
Minor version of the lower end point if requested, else 0
``<PackageName>_FIND_VERSION_MIN_PATCH``
Patch version of the lower end point if requested, else 0
``<PackageName>_FIND_VERSION_MIN_TWEAK``
Tweak version of the lower end point if requested, else 0
``<PackageName>_FIND_VERSION_MIN_COUNT``
Number of version components of the lower end point, 0 to 4
``<PackageName>_FIND_VERSION_MAX``
Full requested version string of the upper end point of the range
``<PackageName>_FIND_VERSION_MAX_MAJOR``
Major version of the upper end point if requested, else 0
``<PackageName>_FIND_VERSION_MAX_MINOR``
Minor version of the upper end point if requested, else 0
``<PackageName>_FIND_VERSION_MAX_PATCH``
Patch version of the upper end point if requested, else 0
``<PackageName>_FIND_VERSION_MAX_TWEAK``
Tweak version of the upper end point if requested, else 0
``<PackageName>_FIND_VERSION_MAX_COUNT``
Number of version components of the upper end point, 0 to 4
Regardless of whether a single version or a version range is specified, the
variable ``<PackageName>_FIND_VERSION_COMPLETE`` will be defined and will hold
the full requested version string as specified.
In Module mode the loaded find module is responsible to honor the
request detailed by these variables; see the find module for details.
In Config mode ``find_package`` handles ``REQUIRED``, ``QUIET``, and

View File

@ -8,6 +8,8 @@ find_path
.. |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|
@ -17,7 +19,8 @@ find_path
.. |CMAKE_XXX_PATH| replace:: :variable:`CMAKE_INCLUDE_PATH`
.. |CMAKE_XXX_MAC_PATH| replace:: :variable:`CMAKE_FRAMEWORK_PATH`
.. |SYSTEM_ENVIRONMENT_PATH_XXX| replace:: The directories in ``PATH`` and ``INCLUDE``.
.. |SYSTEM_ENVIRONMENT_PATH_XXX| replace:: The directories in ``INCLUDE``
and ``PATH``.
.. |SYSTEM_ENVIRONMENT_PATH_WINDOWS_XXX| replace:: On Windows hosts:
``<prefix>/include/<arch>`` if :variable:`CMAKE_LIBRARY_ARCHITECTURE`
is set, and |SYSTEM_ENVIRONMENT_PREFIX_PATH_XXX_SUBDIR|.

View File

@ -8,6 +8,8 @@ find_program
.. |prefix_XXX_SUBDIR| replace:: ``<prefix>/[s]bin``
.. |entry_XXX_SUBDIR| replace:: ``<entry>/[s]bin``
.. |FIND_XXX_REGISTRY_VIEW_DEFAULT| replace:: ``BOTH``
.. |FIND_PACKAGE_ROOT_PREFIX_PATH_XXX| replace::
|FIND_PACKAGE_ROOT_PREFIX_PATH_XXX_SUBDIR|
.. |CMAKE_PREFIX_PATH_XXX| replace::

View File

@ -14,9 +14,12 @@ semicolon or whitespace.
All commands between ``foreach`` and the matching ``endforeach`` are recorded
without being invoked. Once the ``endforeach`` is evaluated, the recorded
list of commands is invoked once for each item in ``<items>``.
At the beginning of each iteration the variable ``loop_var`` will be set
At the beginning of each iteration the variable ``<loop_var>`` will be set
to the value of the current item.
The scope of ``<loop_var>`` is restricted to the loop scope. See policy
:policy:`CMP0124` for details.
The commands :command:`break` and :command:`continue` provide means to
escape from the normal control flow.
@ -47,7 +50,7 @@ of undocumented behavior that may change in future releases.
.. code-block:: cmake
foreach(loop_var IN [LISTS [<lists>]] [ITEMS [<items>]])
foreach(<loop_var> IN [LISTS [<lists>]] [ITEMS [<items>]])
In this variant, ``<lists>`` is a whitespace or semicolon
separated list of list-valued variables. The ``foreach``
@ -82,3 +85,56 @@ yields
-- X=6
-- X=7
-- X=8
.. code-block:: cmake
foreach(<loop_var>... IN ZIP_LISTS <lists>)
.. versionadded:: 3.17
In this variant, ``<lists>`` is a whitespace or semicolon
separated list of list-valued variables. The ``foreach``
command iterates over each list simultaneously setting the
iteration variables as follows:
- if the only ``loop_var`` given, then it sets a series of
``loop_var_N`` variables to the current item from the
corresponding list;
- if multiple variable names passed, their count should match
the lists variables count;
- if any of the lists are shorter, the corresponding iteration
variable is not defined for the current iteration.
.. code-block:: cmake
list(APPEND English one two three four)
list(APPEND Bahasa satu dua tiga)
foreach(num IN ZIP_LISTS English Bahasa)
message(STATUS "num_0=${num_0}, num_1=${num_1}")
endforeach()
foreach(en ba IN ZIP_LISTS English Bahasa)
message(STATUS "en=${en}, ba=${ba}")
endforeach()
yields
::
-- num_0=one, num_1=satu
-- num_0=two, num_1=dua
-- num_0=three, num_1=tiga
-- num_0=four, num_1=
-- en=one, ba=satu
-- en=two, ba=dua
-- en=three, ba=tiga
-- en=four, ba=
See Also
^^^^^^^^
* :command:`break`
* :command:`continue`
* :command:`endforeach`
* :command:`while`

View File

@ -44,11 +44,16 @@ can be invoked through any of
foo()
Foo()
FOO()
cmake_language(CALL foo)
and so on. However, it is strongly recommended to stay with the
case chosen in the function definition. Typically functions use
all-lowercase names.
.. versionadded:: 3.18
The :command:`cmake_language(CALL ...)` command can also be used to
invoke the function.
Arguments
^^^^^^^^^
@ -68,3 +73,9 @@ argument. Referencing to ``ARGV#`` arguments beyond ``ARGC`` have
undefined behavior. Checking that ``ARGC`` is greater than ``#`` is
the only way to ensure that ``ARGV#`` was passed to the function as an
extra argument.
See Also
^^^^^^^^
* :command:`endfunction`
* :command:`return`

View File

@ -8,9 +8,16 @@ Get a property of ``DIRECTORY`` scope.
get_directory_property(<variable> [DIRECTORY <dir>] <prop-name>)
Stores a property of directory scope in the named ``<variable>``.
The ``DIRECTORY`` argument specifies another directory from which
to retrieve the property value instead of the current directory.
The specified directory must have already been traversed by CMake.
Relative paths are treated as relative to the
current source directory. CMake must already know about the directory,
either by having added it through a call to :command:`add_subdirectory`
or being the top level directory.
.. versionadded:: 3.19
``<dir>`` may reference a binary directory.
If the property is not defined for the nominated directory scope,
an empty string is returned. In the case of ``INHERITED`` properties,

View File

@ -3,6 +3,17 @@ get_filename_component
Get a specific component of a full filename.
.. versionchanged:: 3.20
This command has been superseded by :command:`cmake_path` command, except
``REALPATH`` now offered by :ref:`file(REAL_PATH)<REAL_PATH>` command and
``PROGRAM`` now available in :command:`separate_arguments(PROGRAM)` command.
.. versionchanged:: 3.24
The undocumented feature offering the capability to query the ``Windows``
registry is superseded by
:ref:`cmake_host_system_information(QUERY WINDOWS_REGISTRY)<Query Windows registry>`
command.
.. code-block:: cmake
get_filename_component(<var> <FileName> <mode> [CACHE])
@ -14,11 +25,14 @@ Sets ``<var>`` to a component of ``<FileName>``, where ``<mode>`` is one of:
DIRECTORY = Directory without file name
NAME = File name without directory
EXT = File name longest extension (.b.c from d/a.b.c)
NAME_WE = File name without directory or longest extension
NAME_WE = File name with neither the directory nor the longest extension
LAST_EXT = File name last extension (.c from d/a.b.c)
NAME_WLE = File name without directory or last extension
NAME_WLE = File name with neither the directory nor the last extension
PATH = Legacy alias for DIRECTORY (use for CMake <= 2.8.11)
.. versionadded:: 3.14
Added the ``LAST_EXT`` and ``NAME_WLE`` modes.
Paths are returned with forward slashes and have no trailing slashes.
If the optional ``CACHE`` argument is specified, the result variable is
added to the cache.
@ -27,6 +41,8 @@ added to the cache.
get_filename_component(<var> <FileName> <mode> [BASE_DIR <dir>] [CACHE])
.. versionadded:: 3.4
Sets ``<var>`` to the absolute path of ``<FileName>``, where ``<mode>`` is one
of:

View File

@ -9,7 +9,8 @@ Get a property.
<GLOBAL |
DIRECTORY [<dir>] |
TARGET <target> |
SOURCE <source> |
SOURCE <source>
[DIRECTORY <dir> | TARGET_DIRECTORY <target>] |
INSTALL <file> |
TEST <test> |
CACHE <entry> |
@ -30,18 +31,47 @@ It must be one of the following:
Scope defaults to the current directory but another
directory (already processed by CMake) may be named by the
full or relative path ``<dir>``.
Relative paths are treated as relative to the current source directory.
See also the :command:`get_directory_property` command.
.. versionadded:: 3.19
``<dir>`` may reference a binary directory.
``TARGET``
Scope must name one existing target.
See also the :command:`get_target_property` command.
``SOURCE``
Scope must name one source file.
Scope must name one source file. By default, the source file's property
will be read from the current source directory's scope.
.. versionadded:: 3.18
Directory scope can be overridden with one of the following sub-options:
``DIRECTORY <dir>``
The source file property will be read from the ``<dir>`` directory's
scope. CMake must already know about
the directory, either by having added it through a call
to :command:`add_subdirectory` or ``<dir>`` being the top level directory.
Relative paths are treated as relative to the current source directory.
.. versionadded:: 3.19
``<dir>`` may reference a binary directory.
``TARGET_DIRECTORY <target>``
The source file property will be read from the directory scope in which
``<target>`` was created (``<target>`` must therefore already exist).
See also the :command:`get_source_file_property` command.
``INSTALL``
.. versionadded:: 3.1
Scope must name one installed file path.
``TEST``
Scope must name one existing test.
See also the :command:`get_test_property` command.
``CACHE``
Scope must name one cache entry.
@ -64,3 +94,8 @@ If ``BRIEF_DOCS`` or ``FULL_DOCS`` is given then the variable is set to a
string containing documentation for the requested property. If
documentation is requested for a property that has not been defined
``NOTFOUND`` is returned.
.. note::
The :prop_sf:`GENERATED` source file property may be globally visible.
See its documentation for details.

View File

@ -5,18 +5,43 @@ Get a property for a source file.
.. code-block:: cmake
get_source_file_property(VAR file property)
get_source_file_property(<variable> <file>
[DIRECTORY <dir> | TARGET_DIRECTORY <target>]
<property>)
Gets a property from a source file. The value of the property is
stored in the variable ``VAR``. If the source property is not found, the
behavior depends on whether it has been defined to be an ``INHERITED`` property
or not (see :command:`define_property`). Non-inherited properties will set
``VAR`` to "NOTFOUND", whereas inherited properties will search the relevant
parent scope as described for the :command:`define_property` command and
if still unable to find the property, ``VAR`` will be set to an empty string.
stored in the specified ``<variable>``. If the source property is not found,
the behavior depends on whether it has been defined to be an ``INHERITED``
property or not (see :command:`define_property`). Non-inherited properties
will set ``variable`` to ``NOTFOUND``, whereas inherited properties will search
the relevant parent scope as described for the :command:`define_property`
command and if still unable to find the property, ``variable`` will be set to
an empty string.
By default, the source file's property will be read from the current source
directory's scope.
.. versionadded:: 3.18
Directory scope can be overridden with one of the following sub-options:
``DIRECTORY <dir>``
The source file property will be read from the ``<dir>`` directory's
scope. CMake must already know about that source directory, either by
having added it through a call to :command:`add_subdirectory` or ``<dir>``
being the top level source directory. Relative paths are treated as
relative to the current source directory.
``TARGET_DIRECTORY <target>``
The source file property will be read from the directory scope in which
``<target>`` was created (``<target>`` must therefore already exist).
Use :command:`set_source_files_properties` to set property values. Source
file properties usually control how the file is built. One property that is
always there is :prop_sf:`LOCATION`.
See also the more general :command:`get_property` command.
.. note::
The :prop_sf:`GENERATED` source file property may be globally visible.
See its documentation for details.

View File

@ -5,15 +5,15 @@ Get a property from a target.
.. code-block:: cmake
get_target_property(VAR target property)
get_target_property(<VAR> target property)
Get a property from a target. The value of the property is stored in
the variable ``VAR``. If the target property is not found, the behavior
the variable ``<VAR>``. If the target property is not found, the behavior
depends on whether it has been defined to be an ``INHERITED`` property
or not (see :command:`define_property`). Non-inherited properties will
set ``VAR`` to ``NOTFOUND``, whereas inherited properties will search the
relevant parent scope as described for the :command:`define_property`
command and if still unable to find the property, ``VAR`` will be set to
set ``<VAR>`` to ``<VAR>-NOTFOUND``, whereas inherited properties will search
the relevant parent scope as described for the :command:`define_property`
command and if still unable to find the property, ``<VAR>`` will be set to
an empty string.
Use :command:`set_target_properties` to set target property values.

View File

@ -16,6 +16,7 @@ relevant parent scope as described for the :command:`define_property`
command and if still unable to find the property, ``VAR`` will be set to
an empty string.
For a list of standard properties you can type ``cmake --help-property-list``.
For a list of standard properties you can type
:option:`cmake --help-property-list`.
See also the more general :command:`get_property` command.

View File

@ -38,39 +38,80 @@ The following syntax applies to the ``condition`` argument of
the ``if``, ``elseif`` and :command:`while` clauses.
Compound conditions are evaluated in the following order of precedence:
Innermost parentheses are evaluated first. Next come unary tests such
as ``EXISTS``, ``COMMAND``, and ``DEFINED``. Then binary tests such as
``EQUAL``, ``LESS``, ``LESS_EQUAL``, ``GREATER``, ``GREATER_EQUAL``,
``STREQUAL``, ``STRLESS``, ``STRLESS_EQUAL``, ``STRGREATER``,
``STRGREATER_EQUAL``, ``VERSION_EQUAL``, ``VERSION_LESS``,
``VERSION_LESS_EQUAL``, ``VERSION_GREATER``, ``VERSION_GREATER_EQUAL``,
and ``MATCHES``. Then the boolean operators in the order ``NOT``, ``AND``,
and finally ``OR``.
Possible conditions are:
1. Parentheses.
2. Unary tests such as `EXISTS`_, `COMMAND`_, and `DEFINED`_.
3. Binary tests such as `EQUAL`_, `LESS`_, `LESS_EQUAL`_, `GREATER`_,
`GREATER_EQUAL`_, `STREQUAL`_, `STRLESS`_, `STRLESS_EQUAL`_,
`STRGREATER`_, `STRGREATER_EQUAL`_, `VERSION_EQUAL`_, `VERSION_LESS`_,
`VERSION_LESS_EQUAL`_, `VERSION_GREATER`_, `VERSION_GREATER_EQUAL`_,
`PATH_EQUAL`_, and `MATCHES`_.
4. Unary logical operator `NOT`_.
5. Binary logical operators `AND`_ and `OR`_, from left to right,
without any short-circuit.
Basic Expressions
"""""""""""""""""
``if(<constant>)``
True if the constant is ``1``, ``ON``, ``YES``, ``TRUE``, ``Y``,
or a non-zero number. False if the constant is ``0``, ``OFF``,
or a non-zero number (including floating point numbers).
False if the constant is ``0``, ``OFF``,
``NO``, ``FALSE``, ``N``, ``IGNORE``, ``NOTFOUND``, the empty string,
or ends in the suffix ``-NOTFOUND``. Named boolean constants are
case-insensitive. If the argument is not one of these specific
constants, it is treated as a variable or string and the following
signature is used.
constants, it is treated as a variable or string (see `Variable Expansion`_
further below) and one of the following two forms applies.
``if(<variable|string>)``
``if(<variable>)``
True if given a variable that is defined to a value that is not a false
constant. False otherwise. (Note macro arguments are not variables.)
constant. False otherwise, including if the variable is undefined.
Note that macro arguments are not variables.
:ref:`Environment Variables <CMake Language Environment Variables>` also
cannot be tested this way, e.g. ``if(ENV{some_var})`` will always evaluate
to false.
``if(<string>)``
A quoted string always evaluates to false unless:
* The string's value is one of the true constants, or
* Policy :policy:`CMP0054` is not set to ``NEW`` and the string's value
happens to be a variable name that is affected by :policy:`CMP0054`'s
behavior.
Logic Operators
"""""""""""""""
.. _NOT:
``if(NOT <condition>)``
True if the condition is not true.
.. _AND:
``if(<cond1> AND <cond2>)``
True if both conditions would be considered true individually.
.. _OR:
``if(<cond1> OR <cond2>)``
True if either condition would be considered true individually.
``if((condition) AND (condition OR (condition)))``
The conditions inside the parenthesis are evaluated first and then
the remaining condition is evaluated as in the other examples.
Where there are nested parenthesis the innermost are evaluated as part
of evaluating the condition that contains them.
Existence Checks
""""""""""""""""
.. _COMMAND:
``if(COMMAND command-name)``
True if the given name is a command, macro or function that can be
invoked.
@ -85,14 +126,44 @@ Possible conditions are:
(in any directory).
``if(TEST test-name)``
True if the given name is an existing test name created by the
:command:`add_test` command.
.. versionadded:: 3.3
True if the given name is an existing test name created by the
:command:`add_test` command.
.. _DEFINED:
``if(DEFINED <name>|CACHE{<name>}|ENV{<name>})``
True if a variable, cache variable or environment variable
with given ``<name>`` is defined. The value of the variable
does not matter. Note the following caveats:
* Macro arguments are not variables.
* It is not possible to test directly whether a `<name>` is a non-cache
variable. The expression ``if(DEFINED someName)`` will evaluate to true
if either a cache or non-cache variable ``someName`` exists. In
comparison, the expression ``if(DEFINED CACHE{someName})`` will only
evaluate to true if a cache variable ``someName`` exists. Both expressions
need to be tested if you need to know whether a non-cache variable exists:
``if(DEFINED someName AND NOT DEFINED CACHE{someName})``.
.. versionadded:: 3.14
Added support for ``CACHE{<name>}`` variables.
``if(<variable|string> IN_LIST <variable>)``
.. versionadded:: 3.3
True if the given element is contained in the named list variable.
File Operations
"""""""""""""""
.. _EXISTS:
``if(EXISTS path-to-file-or-directory)``
True if the named file or directory exists. Behavior is well-defined
only for full paths. Resolves symbolic links, i.e. if the named file or
directory is a symbolic link, returns true if the target of the
symbolic link exists.
only for explicit full paths (a leading ``~/`` is not expanded as
a home directory and is considered a relative path).
Resolves symbolic links, i.e. if the named file or directory is a
symbolic link, returns true if the target of the symbolic link exists.
``if(file1 IS_NEWER_THAN file2)``
True if ``file1`` is newer than ``file2`` or if one of the two files doesn't
@ -111,52 +182,97 @@ Possible conditions are:
only for full paths.
``if(IS_ABSOLUTE path)``
True if the given path is an absolute path.
True if the given path is an absolute path. Note the following special
cases:
* An empty ``path`` evaluates to false.
* On Windows hosts, any ``path`` that begins with a drive letter and colon
(e.g. ``C:``), a forward slash or a backslash will evaluate to true.
This means a path like ``C:no\base\dir`` will evaluate to true, even
though the non-drive part of the path is relative.
* On non-Windows hosts, any ``path`` that begins with a tilde (``~``)
evaluates to true.
Comparisons
"""""""""""
.. _MATCHES:
``if(<variable|string> MATCHES regex)``
True if the given string or variable's value matches the given regular
condition. See :ref:`Regex Specification` for regex format.
``()`` groups are captured in :variable:`CMAKE_MATCH_<n>` variables.
expression. See :ref:`Regex Specification` for regex format.
.. versionadded:: 3.9
``()`` groups are captured in :variable:`CMAKE_MATCH_<n>` variables.
.. _LESS:
``if(<variable|string> LESS <variable|string>)``
True if the given string or variable's value is a valid number and less
than that on the right.
.. _GREATER:
``if(<variable|string> GREATER <variable|string>)``
True if the given string or variable's value is a valid number and greater
than that on the right.
.. _EQUAL:
``if(<variable|string> EQUAL <variable|string>)``
True if the given string or variable's value is a valid number and equal
to that on the right.
.. _LESS_EQUAL:
``if(<variable|string> LESS_EQUAL <variable|string>)``
True if the given string or variable's value is a valid number and less
than or equal to that on the right.
.. versionadded:: 3.7
True if the given string or variable's value is a valid number and less
than or equal to that on the right.
.. _GREATER_EQUAL:
``if(<variable|string> GREATER_EQUAL <variable|string>)``
True if the given string or variable's value is a valid number and greater
than or equal to that on the right.
.. versionadded:: 3.7
True if the given string or variable's value is a valid number and greater
than or equal to that on the right.
.. _STRLESS:
``if(<variable|string> STRLESS <variable|string>)``
True if the given string or variable's value is lexicographically less
than the string or variable on the right.
.. _STRGREATER:
``if(<variable|string> STRGREATER <variable|string>)``
True if the given string or variable's value is lexicographically greater
than the string or variable on the right.
.. _STREQUAL:
``if(<variable|string> STREQUAL <variable|string>)``
True if the given string or variable's value is lexicographically equal
to the string or variable on the right.
.. _STRLESS_EQUAL:
``if(<variable|string> STRLESS_EQUAL <variable|string>)``
True if the given string or variable's value is lexicographically less
than or equal to the string or variable on the right.
.. versionadded:: 3.7
True if the given string or variable's value is lexicographically less
than or equal to the string or variable on the right.
.. _STRGREATER_EQUAL:
``if(<variable|string> STRGREATER_EQUAL <variable|string>)``
True if the given string or variable's value is lexicographically greater
than or equal to the string or variable on the right.
.. versionadded:: 3.7
True if the given string or variable's value is lexicographically greater
than or equal to the string or variable on the right.
Version Comparisons
"""""""""""""""""""
.. _VERSION_LESS:
``if(<variable|string> VERSION_LESS <variable|string>)``
Component-wise integer version number comparison (version format is
@ -164,43 +280,72 @@ Possible conditions are:
Any non-integer version component or non-integer trailing part of a version
component effectively truncates the string at that point.
.. _VERSION_GREATER:
``if(<variable|string> VERSION_GREATER <variable|string>)``
Component-wise integer version number comparison (version format is
``major[.minor[.patch[.tweak]]]``, omitted components are treated as zero).
Any non-integer version component or non-integer trailing part of a version
component effectively truncates the string at that point.
.. _VERSION_EQUAL:
``if(<variable|string> VERSION_EQUAL <variable|string>)``
Component-wise integer version number comparison (version format is
``major[.minor[.patch[.tweak]]]``, omitted components are treated as zero).
Any non-integer version component or non-integer trailing part of a version
component effectively truncates the string at that point.
.. _VERSION_LESS_EQUAL:
``if(<variable|string> VERSION_LESS_EQUAL <variable|string>)``
Component-wise integer version number comparison (version format is
``major[.minor[.patch[.tweak]]]``, omitted components are treated as zero).
Any non-integer version component or non-integer trailing part of a version
component effectively truncates the string at that point.
.. versionadded:: 3.7
Component-wise integer version number comparison (version format is
``major[.minor[.patch[.tweak]]]``, omitted components are treated as zero).
Any non-integer version component or non-integer trailing part of a version
component effectively truncates the string at that point.
.. _VERSION_GREATER_EQUAL:
``if(<variable|string> VERSION_GREATER_EQUAL <variable|string>)``
Component-wise integer version number comparison (version format is
``major[.minor[.patch[.tweak]]]``, omitted components are treated as zero).
Any non-integer version component or non-integer trailing part of a version
component effectively truncates the string at that point.
.. versionadded:: 3.7
Component-wise integer version number comparison (version format is
``major[.minor[.patch[.tweak]]]``, omitted components are treated as zero).
Any non-integer version component or non-integer trailing part of a version
component effectively truncates the string at that point.
``if(<variable|string> IN_LIST <variable>)``
True if the given element is contained in the named list variable.
Path Comparisons
""""""""""""""""
``if(DEFINED <name>|CACHE{<name>}|ENV{<name>})``
True if a variable, cache variable or environment variable
with given ``<name>`` is defined. The value of the variable
does not matter. Note that macro arguments are not variables.
.. _PATH_EQUAL:
``if((condition) AND (condition OR (condition)))``
The conditions inside the parenthesis are evaluated first and then
the remaining condition is evaluated as in the previous examples.
Where there are nested parenthesis the innermost are evaluated as part
of evaluating the condition that contains them.
``if(<variable|string> PATH_EQUAL <variable|string>)``
.. versionadded:: 3.24
Compares the two paths component-by-component. Only if every component of
both paths match will the two paths compare equal. Multiple path separators
are effectively collapsed into a single separator, but note that backslashes
are not converted to forward slashes. No other
:ref:`path normalization <Normalization>` is performed.
Component-wise comparison is superior to string-based comparison due to the
handling of multiple path separators. In the following example, the
expression evaluates to true using ``PATH_EQUAL``, but false with
``STREQUAL``:
.. code-block:: cmake
# comparison is TRUE
if ("/a//b/c" PATH_EQUAL "/a/b/c")
...
endif()
# comparison is FALSE
if ("/a//b/c" STREQUAL "/a/b/c")
...
endif()
See :ref:`cmake_path(COMPARE) <Path COMPARE>` for more details.
Variable Expansion
^^^^^^^^^^^^^^^^^^
@ -268,13 +413,21 @@ above-documented condition syntax accepts ``<variable|string>``:
tested to see if they are boolean constants, if so they are used as
such, otherwise they are assumed to be variables and are dereferenced.
To prevent ambiguity, potential variable or keyword names can be
specified in a :ref:`Quoted Argument` or a :ref:`Bracket Argument`.
A quoted or bracketed variable or keyword will be interpreted as a
string and not dereferenced or interpreted.
See policy :policy:`CMP0054`.
.. versionchanged:: 3.1
To prevent ambiguity, potential variable or keyword names can be
specified in a :ref:`Quoted Argument` or a :ref:`Bracket Argument`.
A quoted or bracketed variable or keyword will be interpreted as a
string and not dereferenced or interpreted.
See policy :policy:`CMP0054`.
There is no automatic evaluation for environment or cache
:ref:`Variable References`. Their values must be referenced as
``$ENV{<name>}`` or ``$CACHE{<name>}`` wherever the above-documented
condition syntax accepts ``<variable|string>``.
See also
^^^^^^^^
* :command:`else`
* :command:`elseif`
* :command:`endif`

View File

@ -21,6 +21,7 @@ specify the type of project, id (``GUID``) of the project and the name of
the target platform. This is useful for projects requiring values
other than the default (e.g. WIX projects).
If the imported project has different configuration names than the
current project, set the :prop_tgt:`MAP_IMPORTED_CONFIG_<CONFIG>`
target property to specify the mapping.
.. versionadded:: 3.9
If the imported project has different configuration names than the
current project, set the :prop_tgt:`MAP_IMPORTED_CONFIG_<CONFIG>`
target property to specify the mapping.

View File

@ -1,6 +1,8 @@
include_guard
-------------
.. versionadded:: 3.10
Provides an include guard for the file currently being processed by CMake.
.. code-block:: cmake

View File

@ -9,19 +9,30 @@ Synopsis
.. parsed-literal::
install(`TARGETS`_ <target>... [...])
install(`IMPORTED_RUNTIME_ARTIFACTS`_ <target>... [...])
install({`FILES`_ | `PROGRAMS`_} <file>... [...])
install(`DIRECTORY`_ <dir>... [...])
install(`SCRIPT`_ <file> [...])
install(`CODE`_ <code> [...])
install(`EXPORT`_ <export-name> [...])
install(`RUNTIME_DEPENDENCY_SET`_ <set-name> [...])
Introduction
^^^^^^^^^^^^
This command generates installation rules for a project. Rules
specified by calls to this command within a source directory are
executed in order during installation. The order across directories
is not defined.
This command generates installation rules for a project. Install rules
specified by calls to the ``install()`` command within a source directory
are executed in order during installation.
.. versionchanged:: 3.14
Install rules in subdirectories
added by calls to the :command:`add_subdirectory` command are interleaved
with those in the parent directory to run in the order declared (see
policy :policy:`CMP0082`).
.. versionchanged:: 3.22
The environment variable :envvar:`CMAKE_INSTALL_MODE` can override the
default copying behavior of :command:`install()`.
There are multiple signatures for this command. Some of them define
installation options for files and targets. Options common to
@ -30,13 +41,23 @@ signatures that specify them. The common options are:
``DESTINATION``
Specify the directory on disk to which a file will be installed.
If a full path (with a leading slash or drive letter) is given
it is used directly. If a relative path is given it is interpreted
relative to the value of the :variable:`CMAKE_INSTALL_PREFIX` variable.
Arguments can be relative or absolute paths.
If a relative path is given it is interpreted relative to the value
of the :variable:`CMAKE_INSTALL_PREFIX` variable.
The prefix can be relocated at install time using the ``DESTDIR``
mechanism explained in the :variable:`CMAKE_INSTALL_PREFIX` variable
documentation.
If an absolute path (with a leading slash or drive letter) is given
it is used verbatim.
As absolute paths are not supported by :manual:`cpack <cpack(1)>` installer
generators, it is preferable to use relative paths throughout.
In particular, there is no need to make paths absolute by prepending
:variable:`CMAKE_INSTALL_PREFIX`; this prefix is used by default if
the DESTINATION is a relative path.
``PERMISSIONS``
Specify permissions for installed files. Valid permissions are
``OWNER_READ``, ``OWNER_WRITE``, ``OWNER_EXECUTE``, ``GROUP_READ``,
@ -64,7 +85,7 @@ signatures that specify them. The common options are:
``COMPONENT``
Specify an installation component name with which the install rule
is associated, such as "runtime" or "development". During
is associated, such as ``Runtime`` or ``Development``. During
component-specific installation only install rules associated with
the given component name will be executed. During a full installation
all components are installed unless marked with ``EXCLUDE_FROM_ALL``.
@ -73,6 +94,8 @@ signatures that specify them. The common options are:
:variable:`CMAKE_INSTALL_DEFAULT_COMPONENT_NAME` variable.
``EXCLUDE_FROM_ALL``
.. versionadded:: 3.6
Specify that the file is excluded from a full installation and only
installed as part of a component-specific installation
@ -85,16 +108,18 @@ signatures that specify them. The common options are:
Specify that it is not an error if the file to be installed does
not exist.
Command signatures that install files may print messages during
installation. Use the :variable:`CMAKE_INSTALL_MESSAGE` variable
to control which messages are printed.
.. versionadded:: 3.1
Command signatures that install files may print messages during
installation. Use the :variable:`CMAKE_INSTALL_MESSAGE` variable
to control which messages are printed.
Many of the ``install()`` variants implicitly create the directories
containing the installed files. If
:variable:`CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS` is set, these
directories will be created with the permissions specified. Otherwise,
they will be created according to the uname rules on Unix-like platforms.
Windows platforms are unaffected.
.. versionadded:: 3.11
Many of the ``install()`` variants implicitly create the directories
containing the installed files. If
:variable:`CMAKE_INSTALL_DEFAULT_DIRECTORY_PERMISSIONS` is set, these
directories will be created with the permissions specified. Otherwise,
they will be created according to the uname rules on Unix-like platforms.
Windows platforms are unaffected.
Installing Targets
^^^^^^^^^^^^^^^^^^
@ -105,8 +130,9 @@ Installing Targets
.. code-block:: cmake
install(TARGETS targets... [EXPORT <export-name>]
[RUNTIME_DEPENDENCIES args...|RUNTIME_DEPENDENCY_SET <set-name>]
[[ARCHIVE|LIBRARY|RUNTIME|OBJECTS|FRAMEWORK|BUNDLE|
PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE]
PRIVATE_HEADER|PUBLIC_HEADER|RESOURCE|FILE_SET <set-name>|CXX_MODULES_BMI]
[DESTINATION <dir>]
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
@ -119,31 +145,40 @@ Installing Targets
)
The ``TARGETS`` form specifies rules for installing targets from a
project. There are several kinds of target files that may be installed:
project. There are several kinds of target :ref:`Output Artifacts`
that may be installed:
``ARCHIVE``
Static libraries are treated as ``ARCHIVE`` targets, except those
marked with the ``FRAMEWORK`` property on macOS (see ``FRAMEWORK``
below.) For DLL platforms (all Windows-based systems including
Cygwin), the DLL import library is treated as an ``ARCHIVE`` target.
On AIX, the linker import file created for executables with
:prop_tgt:`ENABLE_EXPORTS` is treated as an ``ARCHIVE`` target.
Target artifacts of this kind include:
* *Static libraries*
(except on macOS when marked as ``FRAMEWORK``, see below);
* *DLL import libraries*
(on all Windows-based systems including Cygwin; they have extension
``.lib``, in contrast to the ``.dll`` libraries that go to ``RUNTIME``);
* On AIX, the *linker import file* created for executables with
:prop_tgt:`ENABLE_EXPORTS` enabled.
``LIBRARY``
Module libraries are always treated as ``LIBRARY`` targets. For non-
DLL platforms shared libraries are treated as ``LIBRARY`` targets,
except those marked with the ``FRAMEWORK`` property on macOS (see
``FRAMEWORK`` below.)
Target artifacts of this kind include:
* *Shared libraries*, except
- DLLs (these go to ``RUNTIME``, see below),
- on macOS when marked as ``FRAMEWORK`` (see below).
``RUNTIME``
Executables are treated as ``RUNTIME`` objects, except those marked
with the ``MACOSX_BUNDLE`` property on macOS (see ``BUNDLE`` below.)
For DLL platforms (all Windows-based systems including Cygwin), the
DLL part of a shared library is treated as a ``RUNTIME`` target.
Target artifacts of this kind include:
* *Executables*
(except on macOS when marked as ``MACOSX_BUNDLE``, see ``BUNDLE`` below);
* DLLs (on all Windows-based systems including Cygwin; note that the
accompanying import libraries are of kind ``ARCHIVE``).
``OBJECTS``
Object libraries (a simple group of object files) are always treated
as ``OBJECTS`` targets.
.. versionadded:: 3.9
Object files associated with *object libraries*.
``FRAMEWORK``
Both static and shared libraries marked with the ``FRAMEWORK``
@ -169,40 +204,71 @@ project. There are several kinds of target files that may be installed:
Similar to ``PUBLIC_HEADER`` and ``PRIVATE_HEADER``, but for
``RESOURCE`` files. See :prop_tgt:`RESOURCE` for details.
``FILE_SET <set>``
.. versionadded:: 3.23
File sets are defined by the :command:`target_sources(FILE_SET)` command.
If the file set ``<set>`` exists and is ``PUBLIC`` or ``INTERFACE``, any
files in the set are installed under the destination (see below).
The directory structure relative to the file set's base directories is
preserved. For example, a file added to the file set as
``/blah/include/myproj/here.h`` with a base directory ``/blah/include``
would be installed to ``myproj/here.h`` below the destination.
``CXX_MODULES_BMI``
.. note ::
Experimental. Gated by ``CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API``
Any module files from C++ modules from ``PUBLIC`` sources in a file set of
type ``CXX_MODULES`` will be installed to the given ``DESTINATION``. All
modules are placed directly in the destination as no directory structure is
derived from the names of the modules. An empty ``DESTINATION`` may be used
to suppress installing these files (for use in generic code).
For each of these arguments given, the arguments following them only apply
to the target or file type specified in the argument. If none is given, the
installation properties apply to all target types. If only one is given then
only targets of that type will be installed (which can be used to install
just a DLL or just an import library.)
installation properties apply to all target types.
For regular executables, static libraries and shared libraries, the
``DESTINATION`` argument is not required. For these target types, when
``DESTINATION`` is omitted, a default destination will be taken from the
appropriate variable from :module:`GNUInstallDirs`, or set to a built-in
default value if that variable is not defined. The same is true for the
public and private headers associated with the installed targets through the
:prop_tgt:`PUBLIC_HEADER` and :prop_tgt:`PRIVATE_HEADER` target properties.
A destination must always be provided for module libraries, Apple bundles and
frameworks. A destination can be omitted for interface and object libraries,
but they are handled differently (see the discussion of this topic toward the
end of this section).
default value if that variable is not defined. The same is true for file
sets, and the public and private headers associated with the installed
targets through the :prop_tgt:`PUBLIC_HEADER` and :prop_tgt:`PRIVATE_HEADER`
target properties. A destination must always be provided for module libraries,
Apple bundles and frameworks. A destination can be omitted for interface and
object libraries, but they are handled differently (see the discussion of this
topic toward the end of this section).
For shared libraries on DLL platforms, if neither ``RUNTIME`` nor ``ARCHIVE``
destinations are specified, both the ``RUNTIME`` and ``ARCHIVE`` components are
installed to their default destinations. If either a ``RUNTIME`` or ``ARCHIVE``
destination is specified, the component is installed to that destination, and
the other component is not installed. If both ``RUNTIME`` and ``ARCHIVE``
destinations are specified, then both components are installed to their
respective destinations.
The following table shows the target types with their associated variables and
built-in defaults that apply when no destination is given:
================== =============================== ======================
Target Type GNUInstallDirs Variable Built-In Default
================== =============================== ======================
``RUNTIME`` ``${CMAKE_INSTALL_BINDIR}`` ``bin``
``LIBRARY`` ``${CMAKE_INSTALL_LIBDIR}`` ``lib``
``ARCHIVE`` ``${CMAKE_INSTALL_LIBDIR}`` ``lib``
``PRIVATE_HEADER`` ``${CMAKE_INSTALL_INCLUDEDIR}`` ``include``
``PUBLIC_HEADER`` ``${CMAKE_INSTALL_INCLUDEDIR}`` ``include``
================== =============================== ======================
=============================== =============================== ======================
Target Type GNUInstallDirs Variable Built-In Default
=============================== =============================== ======================
``RUNTIME`` ``${CMAKE_INSTALL_BINDIR}`` ``bin``
``LIBRARY`` ``${CMAKE_INSTALL_LIBDIR}`` ``lib``
``ARCHIVE`` ``${CMAKE_INSTALL_LIBDIR}`` ``lib``
``PRIVATE_HEADER`` ``${CMAKE_INSTALL_INCLUDEDIR}`` ``include``
``PUBLIC_HEADER`` ``${CMAKE_INSTALL_INCLUDEDIR}`` ``include``
``FILE_SET`` (type ``HEADERS``) ``${CMAKE_INSTALL_INCLUDEDIR}`` ``include``
=============================== =============================== ======================
Projects wishing to follow the common practice of installing headers into a
project-specific subdirectory will need to provide a destination rather than
rely on the above.
project-specific subdirectory may prefer using file sets with appropriate
paths and base directories. Otherwise, they must provide a ``DESTINATION``
instead of being able to rely on the above (see next example below).
To make packages compliant with distribution filesystem layout policies, if
projects must specify a ``DESTINATION``, it is recommended that they use a
@ -211,7 +277,7 @@ This allows package maintainers to control the install destination by setting
the appropriate cache variables. The following example shows a static library
being installed to the default destination provided by
:module:`GNUInstallDirs`, but with its headers installed to a project-specific
subdirectory that follows the above recommendation:
subdirectory without using file sets:
.. code-block:: cmake
@ -227,6 +293,8 @@ In addition to the common options listed above, each target can accept
the following additional arguments:
``NAMELINK_COMPONENT``
.. versionadded:: 3.12
On some platforms a versioned shared library has a symbolic link such
as::
@ -301,6 +369,11 @@ top level:
See documentation of the :prop_tgt:`EXPORT_NAME` target property to change
the name of the exported target.
If ``EXPORT`` is used and the targets include ``PUBLIC`` or ``INTERFACE``
file sets, all of them must be specified with ``FILE_SET`` arguments. All
``PUBLIC`` or ``INTERFACE`` file sets associated with a target are included
in the export.
``INCLUDES DESTINATION``
This option specifies a list of directories which will be added to the
:prop_tgt:`INTERFACE_INCLUDE_DIRECTORIES` target property of the
@ -308,6 +381,49 @@ top level:
relative path is specified, it is treated as relative to the
``$<INSTALL_PREFIX>``.
``RUNTIME_DEPENDENCY_SET``
.. versionadded:: 3.21
This option causes all runtime dependencies of installed executable, shared
library, and module targets to be added to the specified runtime dependency
set. This set can then be installed with an
`install(RUNTIME_DEPENDENCY_SET)`_ command.
This keyword and the ``RUNTIME_DEPENDENCIES`` keyword are mutually
exclusive.
``RUNTIME_DEPENDENCIES``
.. versionadded:: 3.21
This option causes all runtime dependencies of installed executable, shared
library, and module targets to be installed along with the targets
themselves. The ``RUNTIME``, ``LIBRARY``, ``FRAMEWORK``, and generic
arguments are used to determine the properties (``DESTINATION``,
``COMPONENT``, etc.) of the installation of these dependencies.
``RUNTIME_DEPENDENCIES`` is semantically equivalent to the following pair
of calls:
.. code-block:: cmake
install(TARGETS ... RUNTIME_DEPENDENCY_SET <set-name>)
install(RUNTIME_DEPENDENCY_SET <set-name> args...)
where ``<set-name>`` will be a randomly generated set name.
The ``args...`` may include any of the following keywords supported by
the `install(RUNTIME_DEPENDENCY_SET)`_ command:
* ``DIRECTORIES``
* ``PRE_INCLUDE_REGEXES``
* ``PRE_EXCLUDE_REGEXES``
* ``POST_INCLUDE_REGEXES``
* ``POST_EXCLUDE_REGEXES``
* ``POST_INCLUDE_FILES``
* ``POST_EXCLUDE_FILES``
The ``RUNTIME_DEPENDENCIES`` and ``RUNTIME_DEPENDENCY_SET`` keywords are
mutually exclusive.
One or more groups of properties may be specified in a single call to
the ``TARGETS`` form of this command. A target may be installed more than
once to different locations. Consider hypothetical targets ``myExe``,
@ -338,17 +454,57 @@ targets that link to the object libraries in their implementation.
Installing a target with the :prop_tgt:`EXCLUDE_FROM_ALL` target property
set to ``TRUE`` has undefined behavior.
`install(TARGETS)`_ can install targets that were created in
other directories. When using such cross-directory install rules, running
``make install`` (or similar) from a subdirectory will not guarantee that
targets from other directories are up-to-date. You can use
:command:`target_link_libraries` or :command:`add_dependencies`
to ensure that such out-of-directory targets are built before the
subdirectory-specific install rules are run.
.. versionadded:: 3.3
An install destination given as a ``DESTINATION`` argument may
use "generator expressions" with the syntax ``$<...>``. See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
An install destination given as a ``DESTINATION`` argument may
use "generator expressions" with the syntax ``$<...>``. See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
.. versionadded:: 3.13
`install(TARGETS)`_ can install targets that were created in
other directories. When using such cross-directory install rules, running
``make install`` (or similar) from a subdirectory will not guarantee that
targets from other directories are up-to-date. You can use
:command:`target_link_libraries` or :command:`add_dependencies`
to ensure that such out-of-directory targets are built before the
subdirectory-specific install rules are run.
Installing Imported Runtime Artifacts
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. _`install(IMPORTED_RUNTIME_ARTIFACTS)`:
.. _IMPORTED_RUNTIME_ARTIFACTS:
.. versionadded:: 3.21
.. code-block:: cmake
install(IMPORTED_RUNTIME_ARTIFACTS targets...
[RUNTIME_DEPENDENCY_SET <set-name>]
[[LIBRARY|RUNTIME|FRAMEWORK|BUNDLE]
[DESTINATION <dir>]
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[COMPONENT <component>]
[OPTIONAL] [EXCLUDE_FROM_ALL]
] [...]
)
The ``IMPORTED_RUNTIME_ARTIFACTS`` form specifies rules for installing the
runtime artifacts of imported targets. Projects may do this if they want to
bundle outside executables or modules inside their installation. The
``LIBRARY``, ``RUNTIME``, ``FRAMEWORK``, and ``BUNDLE`` arguments have the
same semantics that they do in the `TARGETS`_ mode. Only the runtime artifacts
of imported targets are installed (except in the case of :prop_tgt:`FRAMEWORK`
libraries, :prop_tgt:`MACOSX_BUNDLE` executables, and :prop_tgt:`BUNDLE`
CFBundles.) For example, headers and import libraries associated with DLLs are
not installed. In the case of :prop_tgt:`FRAMEWORK` libraries,
:prop_tgt:`MACOSX_BUNDLE` executables, and :prop_tgt:`BUNDLE` CFBundles, the
entire directory is installed.
The ``RUNTIME_DEPENDENCY_SET`` option causes the runtime artifacts of the
imported executable, shared library, and module library ``targets`` to be
added to the ``<set-name>`` runtime dependency set. This set can then be
installed with an `install(RUNTIME_DEPENDENCY_SET)`_ command.
Installing Files
^^^^^^^^^^^^^^^^
@ -358,6 +514,12 @@ Installing Files
.. _FILES:
.. _PROGRAMS:
.. note::
If installing header files, consider using file sets defined by
:command:`target_sources(FILE_SET)` instead. File sets associate
headers with a target and they install as part of the target.
.. code-block:: cmake
install(<FILES|PROGRAMS> files...
@ -414,7 +576,8 @@ file type if they wish to explicitly define the install destination.
Projects wishing to follow the common practice of installing headers into a
project-specific subdirectory will need to provide a destination rather than
rely on the above.
rely on the above. Using file sets for headers instead of ``install(FILES)``
would be even better (see :command:`target_sources(FILE_SET)`).
Note that some of the types' built-in defaults use the ``DATAROOT`` directory as
a prefix. The ``DATAROOT`` prefix is calculated similarly to the types, with
@ -427,18 +590,25 @@ projects must specify a ``DESTINATION``, it is recommended that they use a
path that begins with the appropriate :module:`GNUInstallDirs` variable.
This allows package maintainers to control the install destination by setting
the appropriate cache variables. The following example shows how to follow
this advice while installing headers to a project-specific subdirectory:
this advice while installing an image to a project-specific documentation
subdirectory:
.. code-block:: cmake
include(GNUInstallDirs)
install(FILES mylib.h
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/myproj
install(FILES logo.png
DESTINATION ${CMAKE_INSTALL_DOCDIR}/myproj
)
An install destination given as a ``DESTINATION`` argument may
use "generator expressions" with the syntax ``$<...>``. See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
.. versionadded:: 3.4
An install destination given as a ``DESTINATION`` argument may
use "generator expressions" with the syntax ``$<...>``. See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
.. versionadded:: 3.20
An install rename given as a ``RENAME`` argument may
use "generator expressions" with the syntax ``$<...>``. See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
Installing Directories
^^^^^^^^^^^^^^^^^^^^^^
@ -446,6 +616,13 @@ Installing Directories
.. _`install(DIRECTORY)`:
.. _DIRECTORY:
.. note::
To install a directory sub-tree of headers, consider using file sets
defined by :command:`target_sources(FILE_SET)` instead. File sets not only
preserve directory structure, they also associate headers with a target
and install as part of the target.
.. code-block:: cmake
install(DIRECTORY dirs...
@ -476,7 +653,8 @@ permissions specified in the ``FILES`` form of the command, and the
directories will be given the default permissions specified in the
``PROGRAMS`` form of the command.
The ``MESSAGE_NEVER`` option disables file installation status output.
.. versionadded:: 3.1
The ``MESSAGE_NEVER`` option disables file installation status output.
Installation of directories may be controlled with fine granularity
using the ``PATTERN`` or ``REGEX`` options. These "match" options specify a
@ -496,12 +674,13 @@ any expression. For example, the code
.. code-block:: cmake
install(DIRECTORY src/ DESTINATION include/myproj
FILES_MATCHING PATTERN "*.h")
install(DIRECTORY src/ DESTINATION doc/myproj
FILES_MATCHING PATTERN "*.png")
will extract and install header files from a source tree.
will extract and install images from a source tree.
Some options may follow a ``PATTERN`` or ``REGEX`` expression and are applied
Some options may follow a ``PATTERN`` or ``REGEX`` expression as described
under :ref:`string(REGEX) <Regex Specification>` and are applied
only to files or directories matching them. The ``EXCLUDE`` option will
skip the matched file or directory. The ``PERMISSIONS`` option overrides
the permissions setting for the matched file or directory. For
@ -560,10 +739,14 @@ path that begins with the appropriate :module:`GNUInstallDirs` variable.
This allows package maintainers to control the install destination by setting
the appropriate cache variables.
The list of ``dirs...`` given to ``DIRECTORY`` and an install destination
given as a ``DESTINATION`` argument may use "generator expressions"
with the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
manual for available expressions.
.. versionadded:: 3.4
An install destination given as a ``DESTINATION`` argument may
use "generator expressions" with the syntax ``$<...>``. See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
.. versionadded:: 3.5
The list of ``dirs...`` given to ``DIRECTORY`` may use
"generator expressions" too.
Custom Installation Logic
^^^^^^^^^^^^^^^^^^^^^^^^^
@ -576,7 +759,8 @@ Custom Installation Logic
.. code-block:: cmake
install([[SCRIPT <file>] [CODE <code>]]
[COMPONENT <component>] [EXCLUDE_FROM_ALL] [...])
[ALL_COMPONENTS | COMPONENT <component>]
[EXCLUDE_FROM_ALL] [...])
The ``SCRIPT`` form will invoke the given CMake script files during
installation. If the script file name is a relative path it will be
@ -591,10 +775,17 @@ example, the code
will print a message during installation.
``<file>`` or ``<code>`` may use "generator expressions" with the syntax
``$<...>`` (in the case of ``<file>``, this refers to their use in the file
name, not the file's contents). See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
.. versionadded:: 3.21
When the ``ALL_COMPONENTS`` option is given, the custom installation
script code will be executed for every component of a component-specific
installation. This option is mutually exclusive with the ``COMPONENT``
option.
.. versionadded:: 3.14
``<file>`` or ``<code>`` may use "generator expressions" with the syntax
``$<...>`` (in the case of ``<file>``, this refers to their use in the file
name, not the file's contents). See the
:manual:`cmake-generator-expressions(7)` manual for available expressions.
Installing Exports
^^^^^^^^^^^^^^^^^^
@ -605,9 +796,10 @@ Installing Exports
.. code-block:: cmake
install(EXPORT <export-name> DESTINATION <dir>
[NAMESPACE <namespace>] [[FILE <name>.cmake]|
[NAMESPACE <namespace>] [FILE <name>.cmake]
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[CONFIGURATIONS [Debug|Release|...]
[CXX_MODULES_DIRECTORY <directory>]
[EXPORT_LINK_INTERFACE_LIBRARIES]
[COMPONENT <component>]
[EXCLUDE_FROM_ALL])
@ -630,6 +822,13 @@ present, causes the contents of the properties matching
``(IMPORTED_)?LINK_INTERFACE_LIBRARIES(_<CONFIG>)?`` to be exported, when
policy :policy:`CMP0022` is ``NEW``.
.. note::
The installed ``<export-name>.cmake`` file may come with additional
per-configuration ``<export-name>-*.cmake`` files to be loaded by
globbing. Do not use an export name that is the same as the package
name in combination with installing a ``<package-name>-config.cmake``
file or the latter may be incorrectly matched by the glob and loaded.
When a ``COMPONENT`` option is given, the listed ``<component>`` implicitly
depends on all components mentioned in the export set. The exported
``<name>.cmake`` file will require each of the exported components to be
@ -647,13 +846,26 @@ RPM, typically handle this by listing the ``Runtime`` component as a dependency
of the ``Development`` component in the package metadata, ensuring that the
library is always installed if the headers and CMake export file are present.
In addition to cmake language files, the ``EXPORT_ANDROID_MK`` mode maybe
used to specify an export to the android ndk build system. This mode
accepts the same options as the normal export mode. 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.
.. versionadded:: 3.7
In addition to cmake language files, the ``EXPORT_ANDROID_MK`` mode may be
used to specify an export to the android ndk build system. This mode
accepts the same options as the normal export mode. 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.
``CXX_MODULES_DIRECTORY``
.. note ::
Experimental. Gated by ``CMAKE_EXPERIMENTAL_CXX_MODULE_CMAKE_API``
Specify a subdirectory to store C++ module information for targets in the
export set. This directory will be populated with files which add the
necessary target property information to the relevant targets. Note that
without this information, none of the C++ modules which are part of the
targets in the export set will support being imported in consuming targets.
The ``EXPORT`` form is useful to help outside projects use targets built
and installed by the current project. For example, the code
@ -672,7 +884,7 @@ executable from the installation tree using the imported target name
``mp_myexe`` as if the target were built in its own tree.
.. note::
This command supercedes the :command:`install_targets` command and
This command supersedes the :command:`install_targets` command and
the :prop_tgt:`PRE_INSTALL_SCRIPT` and :prop_tgt:`POST_INSTALL_SCRIPT`
target properties. It also replaces the ``FILES`` forms of the
:command:`install_files` and :command:`install_programs` commands.
@ -681,13 +893,82 @@ executable from the installation tree using the imported target name
:command:`install_files`, and :command:`install_programs` commands
is not defined.
Installing Runtime Dependencies
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. _`install(RUNTIME_DEPENDENCY_SET)`:
.. _RUNTIME_DEPENDENCY_SET:
.. versionadded:: 3.21
.. code-block:: cmake
install(RUNTIME_DEPENDENCY_SET <set-name>
[[LIBRARY|RUNTIME|FRAMEWORK]
[DESTINATION <dir>]
[PERMISSIONS permissions...]
[CONFIGURATIONS [Debug|Release|...]]
[COMPONENT <component>]
[NAMELINK_COMPONENT <component>]
[OPTIONAL] [EXCLUDE_FROM_ALL]
] [...]
[PRE_INCLUDE_REGEXES regexes...]
[PRE_EXCLUDE_REGEXES regexes...]
[POST_INCLUDE_REGEXES regexes...]
[POST_EXCLUDE_REGEXES regexes...]
[POST_INCLUDE_FILES files...]
[POST_EXCLUDE_FILES files...]
[DIRECTORIES directories...]
)
Installs a runtime dependency set previously created by one or more
`install(TARGETS)`_ or `install(IMPORTED_RUNTIME_ARTIFACTS)`_ commands. The
dependencies of targets belonging to a runtime dependency set are installed in
the ``RUNTIME`` destination and component on DLL platforms, and in the
``LIBRARY`` destination and component on non-DLL platforms. macOS frameworks
are installed in the ``FRAMEWORK`` destination and component.
Targets built within the build tree will never be installed as runtime
dependencies, nor will their own dependencies, unless the targets themselves
are installed with `install(TARGETS)`_.
The generated install script calls :command:`file(GET_RUNTIME_DEPENDENCIES)`
on the build-tree files to calculate the runtime dependencies. The build-tree
executable files are passed as the ``EXECUTABLES`` argument, the build-tree
shared libraries as the ``LIBRARIES`` argument, and the build-tree modules as
the ``MODULES`` argument. On macOS, if one of the executables is a
:prop_tgt:`MACOSX_BUNDLE`, that executable is passed as the
``BUNDLE_EXECUTABLE`` argument. At most one such bundle executable may be in
the runtime dependency set on macOS. The :prop_tgt:`MACOSX_BUNDLE` property
has no effect on other platforms. Note that
:command:`file(GET_RUNTIME_DEPENDENCIES)` only supports collecting the runtime
dependencies for Windows, Linux and macOS platforms, so
``install(RUNTIME_DEPENDENCY_SET)`` has the same limitation.
The following sub-arguments are forwarded through as the corresponding
arguments to :command:`file(GET_RUNTIME_DEPENDENCIES)` (for those that provide
a non-empty list of directories, regular expressions or files). They all
support :manual:`generator expressions <cmake-generator-expressions(7)>`.
* ``DIRECTORIES <directories>``
* ``PRE_INCLUDE_REGEXES <regexes>``
* ``PRE_EXCLUDE_REGEXES <regexes>``
* ``POST_INCLUDE_REGEXES <regexes>``
* ``POST_EXCLUDE_REGEXES <regexes>``
* ``POST_INCLUDE_FILES <files>``
* ``POST_EXCLUDE_FILES <files>``
Generated Installation Script
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. note::
Use of this feature is not recommended. Please consider using the
:option:`cmake --install` instead.
The ``install()`` command generates a file, ``cmake_install.cmake``, inside
the build directory, which is used internally by the generated install target
and by CPack. You can also invoke this script manually with ``cmake -P``. This
script accepts several variables:
and by CPack. You can also invoke this script manually with
:option:`cmake -P`. This script accepts several variables:
``COMPONENT``
Set this variable to install only a single CPack component as opposed to all

View File

@ -5,7 +5,7 @@ install_files
Use the :command:`install(FILES)` command instead.
This command has been superceded by the :command:`install` command. It is
This command has been superseded by the :command:`install` command. It is
provided for compatibility with older CMake code. The ``FILES`` form is
directly replaced by the ``FILES`` form of the :command:`install`
command. The regexp form can be expressed more clearly using the ``GLOB``

View File

@ -5,7 +5,7 @@ install_programs
Use the :command:`install(PROGRAMS)` command instead.
This command has been superceded by the :command:`install` command. It is
This command has been superseded by the :command:`install` command. It is
provided for compatibility with older CMake code. The ``FILES`` form is
directly replaced by the ``PROGRAMS`` form of the :command:`install`
command. The regexp form can be expressed more clearly using the ``GLOB``

View File

@ -5,7 +5,7 @@ install_targets
Use the :command:`install(TARGETS)` command instead.
This command has been superceded by the :command:`install` command. It is
This command has been superseded by the :command:`install` command. It is
provided for compatibility with older CMake code.
::

View File

@ -11,21 +11,25 @@ Adds the paths in which the linker should search for libraries.
Relative paths given to this command are interpreted as relative to
the current source directory, see :policy:`CMP0015`.
The directories are added to the :prop_dir:`LINK_DIRECTORIES` directory
property for the current ``CMakeLists.txt`` file, converting relative
paths to absolute as needed.
The command will apply only to targets created after it is called.
By default the directories specified are appended onto the current list of
directories. This default behavior can be changed by setting
:variable:`CMAKE_LINK_DIRECTORIES_BEFORE` to ``ON``. By using
``AFTER`` or ``BEFORE`` explicitly, you can select between appending and
prepending, independent of the default.
.. versionadded:: 3.13
The directories are added to the :prop_dir:`LINK_DIRECTORIES` directory
property for the current ``CMakeLists.txt`` file, converting relative
paths to absolute as needed. See the :manual:`cmake-buildsystem(7)`
manual for more on defining buildsystem properties.
Arguments to ``link_directories`` may use "generator expressions" with
the syntax "$<...>". See the :manual:`cmake-generator-expressions(7)`
manual for available expressions. See the :manual:`cmake-buildsystem(7)`
manual for more on defining buildsystem properties.
.. versionadded:: 3.13
By default the directories specified are appended onto the current list of
directories. This default behavior can be changed by setting
:variable:`CMAKE_LINK_DIRECTORIES_BEFORE` to ``ON``. By using
``AFTER`` or ``BEFORE`` explicitly, you can select between appending and
prepending, independent of the default.
.. versionadded:: 3.13
Arguments to ``link_directories`` may use "generator expressions" with
the syntax "$<...>". See the :manual:`cmake-generator-expressions(7)`
manual for available expressions.
.. note::

View File

@ -88,6 +88,8 @@ Returns the list of elements specified by indices from the list.
list(JOIN <list> <glue> <output variable>)
.. versionadded:: 3.12
Returns a string joining all list's elements using the glue string.
To join multiple strings, which are not part of a list, use ``JOIN`` operator
from :command:`string` command.
@ -98,6 +100,8 @@ from :command:`string` command.
list(SUBLIST <list> <begin> <length> <output variable>)
.. versionadded:: 3.12
Returns a sublist of the given list.
If ``<length>`` is 0, an empty list will be returned.
If ``<length>`` is -1 or the list is smaller than ``<begin>+<length>`` then
@ -124,7 +128,9 @@ Modification
list(APPEND <list> [<element> ...])
Appends elements to the list.
Appends elements to the list. If no variable named ``<list>`` exists in the
current scope its value is treated as empty and the elements are appended to
that empty list.
.. _FILTER:
@ -132,11 +138,13 @@ Appends elements to the list.
list(FILTER <list> <INCLUDE|EXCLUDE> REGEX <regular_expression>)
.. versionadded:: 3.6
Includes or removes items from the list that match the mode's pattern.
In ``REGEX`` mode, items will be matched against the given regular expression.
For more information on regular expressions see also the
:command:`string` command.
For more information on regular expressions look under
:ref:`string(REGEX) <Regex Specification>`.
.. _INSERT:
@ -144,7 +152,12 @@ For more information on regular expressions see also the
list(INSERT <list> <element_index> <element> [<element> ...])
Inserts elements to the list to the specified location.
Inserts elements to the list to the specified index. It is an
error to specify an out-of-range index. Valid indexes are 0 to `N`
where `N` is the length of the list, inclusive. An empty list
has length 0. If no variable named ``<list>`` exists in the
current scope its value is treated as empty and the elements are
inserted in that empty list.
.. _POP_BACK:
@ -152,9 +165,12 @@ Inserts elements to the list to the specified location.
list(POP_BACK <list> [<out-var>...])
.. versionadded:: 3.15
If no variable name is given, removes exactly one element. Otherwise,
assign the last element's value to the given variable and removes it,
up to the last variable name given.
with `N` variable names provided, assign the last `N` elements' values
to the given variables and then remove the last `N` values from
``<list>``.
.. _POP_FRONT:
@ -162,9 +178,12 @@ up to the last variable name given.
list(POP_FRONT <list> [<out-var>...])
.. versionadded:: 3.15
If no variable name is given, removes exactly one element. Otherwise,
assign the first element's value to the given variable and removes it,
up to the last variable name given.
with `N` variable names provided, assign the first `N` elements' values
to the given variables and then remove the first `N` values from
``<list>``.
.. _PREPEND:
@ -172,7 +191,11 @@ up to the last variable name given.
list(PREPEND <list> [<element> ...])
Insert elements to the 0th position in the list.
.. versionadded:: 3.15
Insert elements to the 0th position in the list. If no variable named
``<list>`` exists in the current scope its value is treated as empty and
the elements are prepended to that empty list.
.. _REMOVE_ITEM:
@ -206,6 +229,8 @@ but if duplicates are encountered, only the first instance is preserved.
list(TRANSFORM <list> <ACTION> [<SELECTOR>]
[OUTPUT_VARIABLE <output variable>])
.. versionadded:: 3.12
Transforms the list by applying an action to all or, by specifying a
``<SELECTOR>``, to the selected elements of the list, storing the result
in-place or in the specified output variable.
@ -302,12 +327,26 @@ Reverses the contents of the list in-place.
list(SORT <list> [COMPARE <compare>] [CASE <case>] [ORDER <order>])
Sorts the list in-place alphabetically.
.. versionadded:: 3.13
Added the ``COMPARE``, ``CASE``, and ``ORDER`` options.
.. versionadded:: 3.18
Added the ``COMPARE NATURAL`` option.
Use the ``COMPARE`` keyword to select the comparison method for sorting.
The ``<compare>`` option should be one of:
* ``STRING``: Sorts a list of strings alphabetically. This is the
default behavior if the ``COMPARE`` option is not given.
* ``FILE_BASENAME``: Sorts a list of pathnames of files by their basenames.
* ``NATURAL``: Sorts a list of strings using natural order
(see ``strverscmp(3)`` manual), i.e. such that contiguous digits
are compared as whole numbers.
For example: the following list `10.0 1.1 2.1 8.0 2.0 3.1`
will be sorted as `1.1 2.0 2.1 3.1 8.0 10.0` if the ``NATURAL``
comparison is selected where it will be sorted as
`1.1 10.0 2.0 2.1 3.1 8.0` with the ``STRING`` comparison.
Use the ``CASE`` keyword to select a case sensitive or case insensitive
sort mode. The ``<case>`` option should be one of:

View File

@ -42,11 +42,16 @@ can be invoked through any of
foo()
Foo()
FOO()
cmake_language(CALL foo)
and so on. However, it is strongly recommended to stay with the
case chosen in the macro definition. Typically macros use
all-lowercase names.
.. versionadded:: 3.18
The :command:`cmake_language(CALL ...)` command can also be used to
invoke the macro.
Arguments
^^^^^^^^^
@ -91,6 +96,12 @@ just terminate execution of the macro; rather, control is returned
from the scope of the macro call. To avoid confusion, it is recommended
to avoid :command:`return()` in macros altogether.
Unlike a function, the :variable:`CMAKE_CURRENT_FUNCTION`,
:variable:`CMAKE_CURRENT_FUNCTION_LIST_DIR`,
:variable:`CMAKE_CURRENT_FUNCTION_LIST_FILE`,
:variable:`CMAKE_CURRENT_FUNCTION_LIST_LINE` variables are not
set for a macro.
.. _`Argument Caveats`:
Argument Caveats

View File

@ -22,3 +22,7 @@ If neither ``FORCE`` nor ``CLEAR`` is specified,
new values will be marked as advanced, but if a
variable already has an advanced/non-advanced state,
it will not be changed.
.. versionchanged:: 3.17
Variables passed to this command which are not already in the cache
are ignored. See policy :policy:`CMP0102`.

View File

@ -17,17 +17,18 @@ Supported operators are ``+``, ``-``, ``*``, ``/``, ``%``, ``|``, ``&``,
``^``, ``~``, ``<<``, ``>>``, and ``(...)``; they have the same meaning
as in C code.
Hexadecimal numbers are recognized when prefixed with ``0x``, as in C code.
.. versionadded:: 3.13
Hexadecimal numbers are recognized when prefixed with ``0x``, as in C code.
The result is formatted according to the option ``OUTPUT_FORMAT``,
where ``<format>`` is one of
``HEXADECIMAL``
Hexadecimal notation as in C code, i. e. starting with "0x".
``DECIMAL``
Decimal notation. Which is also used if no ``OUTPUT_FORMAT`` option
is specified.
.. versionadded:: 3.13
The result is formatted according to the option ``OUTPUT_FORMAT``,
where ``<format>`` is one of
``HEXADECIMAL``
Hexadecimal notation as in C code, i. e. starting with "0x".
``DECIMAL``
Decimal notation. Which is also used if no ``OUTPUT_FORMAT`` option
is specified.
For example

View File

@ -1,17 +1,40 @@
message
-------
Display a message to the user.
Log a message.
Synopsis
^^^^^^^^
.. parsed-literal::
`General messages`_
message([<mode>] "message text" ...)
`Reporting checks`_
message(<checkState> "message text" ...)
General messages
^^^^^^^^^^^^^^^^
.. code-block:: cmake
message([<mode>] "message to display" ...)
message([<mode>] "message text" ...)
The optional ``<mode>`` keyword determines the type of message:
Record the specified message text in the log. If more than one message
string is given, they are concatenated into a single message with no
separator between the strings.
The optional ``<mode>`` keyword determines the type of message, which
influences the way the message is handled:
``FATAL_ERROR``
CMake Error, stop processing and generation.
The :manual:`cmake(1)` executable will return a non-zero
:ref:`exit code <CMake Exit Code>`.
``SEND_ERROR``
CMake Error, continue processing, but skip generation.
@ -51,20 +74,122 @@ The optional ``<mode>`` keyword determines the type of message:
using this log level would normally only be temporary and would expect to be
removed before releasing the project, packaging up the files, etc.
.. versionadded:: 3.15
Added the ``NOTICE``, ``VERBOSE``, ``DEBUG``, and ``TRACE`` levels.
The CMake command-line tool displays ``STATUS`` to ``TRACE`` messages on stdout
with the message preceded by two hyphens and a space. All other message types
are sent to stderr and are not prefixed with hyphens. The
:manual:`CMake GUI <cmake-gui(1)>` displays all messages in its log area.
The :manual:`curses interface <ccmake(1)>` shows ``STATUS`` to ``TRACE``
messages one at a time on a status line and other messages in an
interactive pop-up box. The ``--log-level`` command-line option to each of
these tools can be used to control which messages will be shown.
interactive pop-up box. The :option:`--log-level <cmake --log-level>`
command-line option to each of these tools can be used to control which
messages will be shown.
Messages of log levels ``NOTICE`` and below will also have each line preceded
by the content of the :variable:`CMAKE_MESSAGE_INDENT` variable (converted to
a single string by concatenating its list items). For ``STATUS`` to ``TRACE``
messages, this indenting content will be inserted after the hyphens.
.. versionadded:: 3.17
To make a log level persist between CMake runs, the
:variable:`CMAKE_MESSAGE_LOG_LEVEL` variable can be set instead.
Note that the command line option takes precedence over the cache variable.
.. versionadded:: 3.16
Messages of log levels ``NOTICE`` and below will have each line preceded
by the content of the :variable:`CMAKE_MESSAGE_INDENT` variable (converted to
a single string by concatenating its list items). For ``STATUS`` to ``TRACE``
messages, this indenting content will be inserted after the hyphens.
.. versionadded:: 3.17
Messages of log levels ``NOTICE`` and below can also have each line preceded
with context of the form ``[some.context.example]``. The content between the
square brackets is obtained by converting the :variable:`CMAKE_MESSAGE_CONTEXT`
list variable to a dot-separated string. The message context will always
appear before any indenting content but after any automatically added leading
hyphens. By default, message context is not shown, it has to be explicitly
enabled by giving the :option:`cmake --log-context`
command-line option or by setting the :variable:`CMAKE_MESSAGE_CONTEXT_SHOW`
variable to true. See the :variable:`CMAKE_MESSAGE_CONTEXT` documentation for
usage examples.
CMake Warning and Error message text displays using a simple markup
language. Non-indented text is formatted in line-wrapped paragraphs
delimited by newlines. Indented text is considered pre-formatted.
Reporting checks
^^^^^^^^^^^^^^^^
.. versionadded:: 3.17
A common pattern in CMake output is a message indicating the start of some
sort of check, followed by another message reporting the result of that check.
For example:
.. code-block:: cmake
message(STATUS "Looking for someheader.h")
#... do the checks, set checkSuccess with the result
if(checkSuccess)
message(STATUS "Looking for someheader.h - found")
else()
message(STATUS "Looking for someheader.h - not found")
endif()
This can be more robustly and conveniently expressed using the ``CHECK_...``
keyword form of the ``message()`` command:
.. code-block:: cmake
message(<checkState> "message" ...)
where ``<checkState>`` must be one of the following:
``CHECK_START``
Record a concise message about the check about to be performed.
``CHECK_PASS``
Record a successful result for a check.
``CHECK_FAIL``
Record an unsuccessful result for a check.
When recording a check result, the command repeats the message from the most
recently started check for which no result has yet been reported, then some
separator characters and then the message text provided after the
``CHECK_PASS`` or ``CHECK_FAIL`` keyword. Check messages are always reported
at ``STATUS`` log level.
Checks may be nested and every ``CHECK_START`` should have exactly one
matching ``CHECK_PASS`` or ``CHECK_FAIL``.
The :variable:`CMAKE_MESSAGE_INDENT` variable can also be used to add
indenting to nested checks if desired. For example:
.. code-block:: cmake
message(CHECK_START "Finding my things")
list(APPEND CMAKE_MESSAGE_INDENT " ")
unset(missingComponents)
message(CHECK_START "Finding partA")
# ... do check, assume we find A
message(CHECK_PASS "found")
message(CHECK_START "Finding partB")
# ... do check, assume we don't find B
list(APPEND missingComponents B)
message(CHECK_FAIL "not found")
list(POP_BACK CMAKE_MESSAGE_INDENT)
if(missingComponents)
message(CHECK_FAIL "missing components: ${missingComponents}")
else()
message(CHECK_PASS "all components found")
endif()
Output from the above would appear something like the following::
-- Finding my things
-- Finding partA
-- Finding partA - found
-- Finding partB
-- Finding partB - not found
-- Finding my things - missing components: B

View File

@ -1,16 +1,18 @@
option
------
Provide an option that the user can optionally select.
Provide a boolean option that the user can optionally select.
.. code-block:: cmake
option(<variable> "<help_text>" [value])
Provides an option for the user to select as ``ON`` or ``OFF``.
If no initial ``<value>`` is provided, ``OFF`` is used.
If ``<variable>`` is already set as a normal variable
If no initial ``<value>`` is provided, boolean ``OFF`` is the default value.
If ``<variable>`` is already set as a normal or cache variable,
then the command does nothing (see policy :policy:`CMP0077`).
If you have options that depend on the values of other options, see
For options that depend on the values of other options, see
the module help for :module:`CMakeDependentOption`.
In CMake project mode, a boolean cache variable is created with the option
value. In CMake script mode, a boolean variable is set with the option value.

View File

@ -20,12 +20,18 @@ Sets the name of the project, and stores it in the variable
``CMakeLists.txt`` also stores the project name in the
variable :variable:`CMAKE_PROJECT_NAME`.
Also sets the variables
Also sets the variables:
* :variable:`PROJECT_SOURCE_DIR`,
:variable:`<PROJECT-NAME>_SOURCE_DIR`
* :variable:`PROJECT_BINARY_DIR`,
:variable:`<PROJECT-NAME>_BINARY_DIR`
:variable:`PROJECT_SOURCE_DIR`, :variable:`<PROJECT-NAME>_SOURCE_DIR`
Absolute path to the source directory for the project.
:variable:`PROJECT_BINARY_DIR`, :variable:`<PROJECT-NAME>_BINARY_DIR`
Absolute path to the binary directory for the project.
:variable:`PROJECT_IS_TOP_LEVEL`, :variable:`<PROJECT-NAME>_IS_TOP_LEVEL`
.. versionadded:: 3.21
Boolean value indicating whether the project is top-level.
Further variables are set by the optional arguments described in the following.
If any of these arguments is not used, then the corresponding variables are
@ -55,10 +61,14 @@ The options are:
* :variable:`PROJECT_VERSION_TWEAK`,
:variable:`<PROJECT-NAME>_VERSION_TWEAK`.
When the ``project()`` command is called from the top-level ``CMakeLists.txt``,
then the version is also stored in the variable :variable:`CMAKE_PROJECT_VERSION`.
.. versionadded:: 3.12
When the ``project()`` command is called from the top-level
``CMakeLists.txt``, then the version is also stored in the variable
:variable:`CMAKE_PROJECT_VERSION`.
``DESCRIPTION <project-description-string>``
.. versionadded:: 3.9
Optional.
Sets the variables
@ -71,7 +81,12 @@ The options are:
When the ``project()`` command is called from the top-level ``CMakeLists.txt``,
then the description is also stored in the variable :variable:`CMAKE_PROJECT_DESCRIPTION`.
.. versionadded:: 3.12
Added the ``<PROJECT-NAME>_DESCRIPTION`` variable.
``HOMEPAGE_URL <url-string>``
.. versionadded:: 3.12
Optional.
Sets the variables
@ -88,29 +103,76 @@ The options are:
Selects which programming languages are needed to build the project.
Supported languages include ``C``, ``CXX`` (i.e. C++), ``CUDA``,
``OBJC`` (i.e. Objective-C), ``OBJCXX``, ``Fortran``, and ``ASM``.
``OBJC`` (i.e. Objective-C), ``OBJCXX``, ``Fortran``, ``HIP``, ``ISPC``, and ``ASM``.
By default ``C`` and ``CXX`` are enabled if no language options are given.
Specify language ``NONE``, or use the ``LANGUAGES`` keyword and list no languages,
to skip enabling any languages.
.. versionadded:: 3.8
Added ``CUDA`` support.
.. versionadded:: 3.16
Added ``OBJC`` and ``OBJCXX`` support.
.. versionadded:: 3.18
Added ``ISPC`` support.
If enabling ``ASM``, list it last so that CMake can check whether
compilers for other languages like ``C`` work for assembly too.
The variables set through the ``VERSION``, ``DESCRIPTION`` and ``HOMEPAGE_URL``
options are intended for use as default values in package metadata and documentation.
.. _`Code Injection`:
Code Injection
^^^^^^^^^^^^^^
If the :variable:`CMAKE_PROJECT_INCLUDE_BEFORE` variable is set, the file
pointed to by that variable will be included as the first step of the
``project()`` command.
A number of variables can be defined by the user to specify files to include
at different points during the execution of the ``project()`` command.
The following outlines the steps performed during a ``project()`` call:
If the :variable:`CMAKE_PROJECT_INCLUDE` or
:variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE` variables are set, the files
they point to will be included as the last step of the ``project()`` command.
If both are set, then :variable:`CMAKE_PROJECT_INCLUDE` will be included before
:variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE`.
* .. versionadded:: 3.15
For every ``project()`` call regardless of the project
name, include the file named by :variable:`CMAKE_PROJECT_INCLUDE_BEFORE`,
if set.
* .. versionadded:: 3.17
If the ``project()`` command specifies ``<PROJECT-NAME>`` as its project
name, include the file named by
:variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE_BEFORE`, if set.
* Set the various project-specific variables detailed in the `Synopsis`_
and `Options`_ sections above.
* For the very first ``project()`` call only:
* If :variable:`CMAKE_TOOLCHAIN_FILE` is set, read it at least once.
It may be read multiple times and it may also be read again when
enabling languages later (see below).
* Set the variables describing the host and target platforms.
Language-specific variables might or might not be set at this point.
On the first run, the only language-specific variables that might be
defined are those a toolchain file may have set. On subsequent runs,
language-specific variables cached from a previous run may be set.
* .. versionadded:: 3.24
Include each file listed in :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES`,
if set. The variable is ignored by CMake thereafter.
* Enable any languages specified in the call, or the default languages if
none were provided. The toolchain file may be re-read when enabling a
language for the first time.
* .. versionadded:: 3.15
For every ``project()`` call regardless of the project
name, include the file named by :variable:`CMAKE_PROJECT_INCLUDE`,
if set.
* If the ``project()`` command specifies ``<PROJECT-NAME>`` as its project
name, include the file named by
:variable:`CMAKE_PROJECT_<PROJECT-NAME>_INCLUDE`, if set.
Usage
^^^^^

View File

@ -5,15 +5,87 @@ Return from a file, directory or function.
.. code-block:: cmake
return()
return([PROPAGATE <var-name>...])
Returns from a file, directory or function. When this command is
encountered in an included file (via :command:`include` or
When this command is encountered in an included file (via :command:`include` or
:command:`find_package`), it causes processing of the current file to stop
and control is returned to the including file. If it is encountered in a
file which is not included by another file, e.g. a ``CMakeLists.txt``,
control is returned to the parent directory if there is one. If return is
called in a function, control is returned to the caller of the function.
file which is not included by another file, e.g. a ``CMakeLists.txt``,
deferred calls scheduled by :command:`cmake_language(DEFER)` are invoked and
control is returned to the parent directory if there is one.
Note that a :command:`macro <macro>`, unlike a :command:`function <function>`,
If ``return()`` is called in a function, control is returned to the caller
of that function. Note that a :command:`macro`, unlike a :command:`function`,
is expanded in place and therefore cannot handle ``return()``.
Policy :policy:`CMP0140` controls the behavior regarding the arguments of the
command. All arguments are ignored unless that policy is set to ``NEW``.
``PROPAGATE``
.. versionadded:: 3.25
This option sets or unsets the specified variables in the parent directory or
function caller scope. This is equivalent to :command:`set(PARENT_SCOPE)` or
:command:`unset(PARENT_SCOPE)` commands, except for the way it interacts
with the :command:`block` command, as described below.
The ``PROPAGATE`` option can be very useful in conjunction with the
:command:`block` command. A :command:`return` will propagate the
specified variables through any enclosing block scopes created by the
:command:`block` commands. Inside a function, this ensures the variables
are propagated to the function's caller, regardless of any blocks within
the function. If not inside a function, it ensures the variables are
propagated to the parent file or directory scope. For example:
.. code-block:: cmake
:caption: CMakeLists.txt
cmake_version_required(VERSION 3.25)
project(example)
set(var1 "top-value")
block(SCOPE_FOR VARIABLES)
add_subdirectory(subDir)
# var1 has the value "block-nested"
endblock()
# var1 has the value "top-value"
.. code-block:: cmake
:caption: subDir/CMakeLists.txt
function(multi_scopes result_var1 result_var2)
block(SCOPE_FOR VARIABLES)
# This would only propagate out of the immediate block, not to
# the caller of the function.
#set(${result_var1} "new-value" PARENT_SCOPE)
#unset(${result_var2} PARENT_SCOPE)
# This propagates the variables through the enclosing block and
# out to the caller of the function.
set(${result_var1} "new-value")
unset(${result_var2})
return(PROPAGATE ${result_var1} ${result_var2})
endblock()
endfunction()
set(var1 "some-value")
set(var2 "another-value")
multi_scopes(var1 var2)
# Now var1 will hold "new-value" and var2 will be unset
block(SCOPE_FOR VARIABLES)
# This return() will set var1 in the directory scope that included us
# via add_subdirectory(). The surrounding block() here does not limit
# propagation to the current file, but the block() in the parent
# directory scope does prevent propagation going any further.
set(var1 "block-nested")
return(PROPAGATE var1)
endblock()
See Also
^^^^^^^^
* :command:`block`

View File

@ -5,7 +5,7 @@ Parse command-line arguments into a semicolon-separated list.
.. code-block:: cmake
separate_arguments(<variable> <mode> <args>)
separate_arguments(<variable> <mode> [PROGRAM [SEPARATE_ARGS]] <args>)
Parses a space-separated string ``<args>`` into a list of items,
and stores this list in semicolon-separated standard form in ``<variable>``.
@ -19,7 +19,7 @@ They are specified by the ``<mode>`` argument which must
be one of the following keywords:
``UNIX_COMMAND``
Arguments are separated by by unquoted whitespace.
Arguments are separated by unquoted whitespace.
Both single-quote and double-quote pairs are respected.
A backslash escapes the next literal character (``\"`` is ``"``);
there are no special escapes (``\n`` is just ``n``).
@ -32,9 +32,43 @@ be one of the following keywords:
MSDN article `Parsing C Command-Line Arguments`_ for details.
``NATIVE_COMMAND``
.. versionadded:: 3.9
Proceeds as in ``WINDOWS_COMMAND`` mode if the host system is Windows.
Otherwise proceeds as in ``UNIX_COMMAND`` mode.
``PROGRAM``
.. versionadded:: 3.19
The first item in ``<args>`` is assumed to be an executable and will be
searched in the system search path or left as a full path. If not found,
``<variable>`` will be empty. Otherwise, ``<variable>`` is a list of 2
elements:
0. Absolute path of the program
1. Any command-line arguments present in ``<args>`` as a string
For example:
.. code-block:: cmake
separate_arguments (out UNIX_COMMAND PROGRAM "cc -c main.c")
* First element of the list: ``/path/to/cc``
* Second element of the list: ``" -c main.c"``
``SEPARATE_ARGS``
When this sub-option of ``PROGRAM`` option is specified, command-line
arguments will be split as well and stored in ``<variable>``.
For example:
.. code-block:: cmake
separate_arguments (out UNIX_COMMAND PROGRAM SEPARATE_ARGS "cc -c main.c")
The contents of ``out`` will be: ``/path/to/cc;-c;main.c``
.. _`Parsing C Command-Line Arguments`: https://msdn.microsoft.com/library/a1y7w461.aspx
.. code-block:: cmake

View File

@ -22,12 +22,17 @@ Set Normal Variable
Sets the given ``<variable>`` in the current function or directory scope.
If the ``PARENT_SCOPE`` option is given the variable will be set in
the scope above the current scope. Each new directory or function
creates a new scope. This command will set the value of a variable
into the parent directory or calling function (whichever is applicable
to the case at hand). The previous state of the variable's value stays the
same in the current scope (e.g., if it was undefined before, it is still
undefined and if it had a value, it is still that value).
the scope above the current scope. Each new directory or :command:`function`
command creates a new scope. A scope can also be created with the
:command:`block` command. This command will set the value of a variable into
the parent directory, calling function or encompassing scope (whichever is
applicable to the case at hand). The previous state of the variable's value
stays the same in the current scope (e.g., if it was undefined before, it is
still undefined and if it had a value, it is still that value).
The :command:`block(PROPAGATE)` and :command:`return(PROPAGATE)` commands can
be used as an alternate method to the :command:`set(PARENT_SCOPE)` and
:command:`unset(PARENT_SCOPE)` commands to update the parent scope.
Set Cache Entry
^^^^^^^^^^^^^^^
@ -68,13 +73,17 @@ users.
If the cache entry does not exist prior to the call or the ``FORCE``
option is given then the cache entry will be set to the given value.
Furthermore, any normal variable binding in the current scope will
be removed to expose the newly cached value to any immediately
following evaluation.
.. note::
The content of the cache variable will not be directly accessible if a normal
variable of the same name already exists (see :ref:`rules of variable
evaluation <CMake Language Variables>`). If policy :policy:`CMP0126` is set
to ``OLD``, any normal variable binding in the current scope will be removed.
It is possible for the cache entry to exist prior to the call but
have no type set if it was created on the :manual:`cmake(1)` command
line by a user through the ``-D<var>=<value>`` option without
line by a user through the :option:`-D\<var\>=\<value\> <cmake -D>` option without
specifying a type. In this case the ``set`` command will add the
type. Furthermore, if the ``<type>`` is ``PATH`` or ``FILEPATH``
and the ``<value>`` provided on the command line is a relative path,

View File

@ -8,12 +8,14 @@ Set a named property in a given scope.
set_property(<GLOBAL |
DIRECTORY [<dir>] |
TARGET [<target1> ...] |
SOURCE [<src1> ...] |
SOURCE [<src1> ...]
[DIRECTORY <dirs> ...]
[TARGET_DIRECTORY <targets> ...] |
INSTALL [<file1> ...] |
TEST [<test1> ...] |
CACHE [<entry1> ...] >
[APPEND] [APPEND_STRING]
PROPERTY <name> [value1 ...])
PROPERTY <name> [<value1> ...])
Sets one property on zero or more objects of a scope.
@ -24,21 +26,46 @@ It must be one of the following:
Scope is unique and does not accept a name.
``DIRECTORY``
Scope defaults to the current directory but another directory
Scope defaults to the current directory but other directories
(already processed by CMake) may be named by full or relative path.
Relative paths are treated as relative to the current source directory.
See also the :command:`set_directory_properties` command.
.. versionadded:: 3.19
``<dir>`` may reference a binary directory.
``TARGET``
Scope may name zero or more existing targets.
See also the :command:`set_target_properties` command.
``SOURCE``
Scope may name zero or more source files. Note that source
file properties are visible only to targets added in the same
directory (``CMakeLists.txt``).
Scope may name zero or more source files. By default, source file properties
are only visible to targets added in the same directory (``CMakeLists.txt``).
.. versionadded:: 3.18
Visibility can be set in other directory scopes using one or both of the
following sub-options:
``DIRECTORY <dirs>...``
The source file property will be set in each of the ``<dirs>``
directories' scopes. CMake must already know about
each of these directories, either by having added them through a call to
:command:`add_subdirectory` or it being the top level source directory.
Relative paths are treated as relative to the current source directory.
.. versionadded:: 3.19
``<dirs>`` may reference a binary directory.
``TARGET_DIRECTORY <targets>...``
The source file property will be set in each of the directory scopes
where any of the specified ``<targets>`` were created (the ``<targets>``
must therefore already exist).
See also the :command:`set_source_files_properties` command.
``INSTALL``
.. versionadded:: 3.1
Scope may name zero or more installed file paths.
These are made available to CPack to influence deployment.
@ -58,6 +85,10 @@ It must be one of the following:
Scope may name zero or more existing tests.
See also the :command:`set_tests_properties` command.
Test property values may be specified using
:manual:`generator expressions <cmake-generator-expressions(7)>`
for tests created by the :command:`add_test(NAME)` signature.
``CACHE``
Scope must name zero or more cache existing entries.
@ -66,7 +97,8 @@ the property to set. Remaining arguments are used to compose the
property value in the form of a semicolon-separated list.
If the ``APPEND`` option is given the list is appended to any existing
property value. If the ``APPEND_STRING`` option is given the string is
property value (except that empty values are ignored and not appended).
If the ``APPEND_STRING`` option is given the string is
appended to any existing property value as string, i.e. it results in a
longer string and not a list of strings. When using ``APPEND`` or
``APPEND_STRING`` with a property defined to support ``INHERITED``
@ -77,3 +109,8 @@ directly set in the nominated scope, the command will behave as though
See the :manual:`cmake-properties(7)` manual for a list of properties
in each scope.
.. note::
The :prop_sf:`GENERATED` source file property may be globally visible.
See its documentation for details.

View File

@ -5,15 +5,39 @@ Source files can have properties that affect how they are built.
.. code-block:: cmake
set_source_files_properties([file1 [file2 [...]]]
PROPERTIES prop1 value1
[prop2 value2 [...]])
set_source_files_properties(<files> ...
[DIRECTORY <dirs> ...]
[TARGET_DIRECTORY <targets> ...]
PROPERTIES <prop1> <value1>
[<prop2> <value2>] ...)
Sets properties associated with source files using a key/value paired
list.
.. versionadded:: 3.18
By default, source file properties are only visible to targets added in the
same directory (``CMakeLists.txt``). Visibility can be set in other directory
scopes using one or both of the following options:
``DIRECTORY <dirs>...``
The source file properties will be set in each of the ``<dirs>``
directories' scopes. CMake must already know about each of these
source directories, either by having added them through a call to
:command:`add_subdirectory` or it being the top level source directory.
Relative paths are treated as relative to the current source directory.
``TARGET_DIRECTORY <targets>...``
The source file properties will be set in each of the directory scopes
where any of the specified ``<targets>`` were created (the ``<targets>``
must therefore already exist).
Use :command:`get_source_file_property` to get property values.
See also the :command:`set_property(SOURCE)` command.
See :ref:`Source File Properties` for the list of properties known
to CMake. Source file properties are visible only to targets added
in the same directory (``CMakeLists.txt``).
to CMake.
.. note::
The :prop_sf:`GENERATED` source file property may be globally visible.
See its documentation for details.

View File

@ -9,8 +9,10 @@ Set a property of the tests.
Sets a property for the tests. If the test is not found, CMake
will report an error.
:manual:`Generator expressions <cmake-generator-expressions(7)>` will be
expanded the same as supported by the test's :command:`add_test` call.
Test property values may be specified using
:manual:`generator expressions <cmake-generator-expressions(7)>`
for tests created by the :command:`add_test(NAME)` signature.
See also the :command:`set_property(TEST)` command.

View File

@ -6,3 +6,7 @@ Set the given variable to the name of the computer.
.. code-block:: cmake
site_name(variable)
On UNIX-like platforms, if the variable ``HOSTNAME`` is set, its value
will be executed as a command expected to print out the host name,
much like the ``hostname`` command-line tool.

View File

@ -11,15 +11,23 @@ There are two different signatures to create source groups.
Defines a group into which sources will be placed in project files.
This is intended to set up file tabs in Visual Studio.
The group is scoped in the directory where the command is called,
and applies to sources in targets created in that directory.
The options are:
``TREE``
.. versionadded:: 3.8
CMake will automatically detect, from ``<src>`` files paths, source groups
it needs to create, to keep structure of source groups analogically to the
actual files and directories structure in the project. Paths of ``<src>``
files will be cut to be relative to ``<root>``.
files will be cut to be relative to ``<root>``. The command fails if the
paths within ``src`` do not start with ``root``.
``PREFIX``
.. versionadded:: 3.8
Source group and files located directly in ``<root>`` path, will be placed
in ``<prefix>`` source groups.
@ -37,14 +45,19 @@ explicitly lists the file with ``FILES`` will be favored, if any.
If no group explicitly lists the file, the *last* group whose
regular expression matches the file will be favored.
The ``<name>`` of the group and ``<prefix>`` argument may contain backslashes
to specify subgroups:
The ``<name>`` of the group and ``<prefix>`` argument may contain forward
slashes or backslashes to specify subgroups. Backslashes need to be escaped
appropriately:
.. code-block:: cmake
source_group(base/subdir ...)
source_group(outer\\inner ...)
source_group(TREE <root> PREFIX sources\\inc ...)
.. versionadded:: 3.18
Allow using forward slashes (``/``) to specify subgroups.
For backwards compatibility, the short-hand signature
.. code-block:: cmake

View File

@ -11,8 +11,6 @@ Synopsis
`Search and Replace`_
string(`FIND`_ <string> <substring> <out-var> [...])
string(`REPLACE`_ <match-string> <replace-string> <out-var> <input>...)
`Regular Expressions`_
string(`REGEX MATCH`_ <match-regex> <out-var> <input>...)
string(`REGEX MATCHALL`_ <match-regex> <out-var> <input>...)
string(`REGEX REPLACE`_ <match-regex> <replace-expr> <out-var> <input>...)
@ -38,15 +36,32 @@ Synopsis
`Generation`_
string(`ASCII`_ <number>... <out-var>)
string(`HEX`_ <string> <out-var>)
string(`CONFIGURE`_ <string> <out-var> [...])
string(`MAKE_C_IDENTIFIER`_ <string> <out-var>)
string(`RANDOM`_ [<option>...] <out-var>)
string(`TIMESTAMP`_ <out-var> [<format string>] [UTC])
string(`UUID`_ <out-var> ...)
`JSON`_
string(JSON <out-var> [ERROR_VARIABLE <error-var>]
{`GET`_ | `TYPE`_ | :ref:`LENGTH <JSONLENGTH>` | `REMOVE`_}
<json-string> <member|index> [<member|index> ...])
string(JSON <out-var> [ERROR_VARIABLE <error-var>]
`MEMBER`_ <json-string>
[<member|index> ...] <index>)
string(JSON <out-var> [ERROR_VARIABLE <error-var>]
`SET`_ <json-string>
<member|index> [<member|index> ...] <value>)
string(JSON <out-var> [ERROR_VARIABLE <error-var>]
`EQUAL`_ <json-string1> <json-string2>)
Search and Replace
^^^^^^^^^^^^^^^^^^
Search and Replace With Plain Strings
"""""""""""""""""""""""""""""""""""""
.. _FIND:
.. code-block:: cmake
@ -74,8 +89,8 @@ so strings containing multi-byte characters may lead to unexpected results.
Replace all occurrences of ``<match_string>`` in the ``<input>``
with ``<replace_string>`` and store the result in the ``<output_variable>``.
Regular Expressions
^^^^^^^^^^^^^^^^^^^
Search and Replace With Regular Expressions
"""""""""""""""""""""""""""""""""""""""""""
.. _`REGEX MATCH`:
@ -87,6 +102,7 @@ Regular Expressions
Match the ``<regular_expression>`` once and store the match in the
``<output_variable>``.
All ``<input>`` arguments are concatenated before matching.
Regular expressions are specified in the subsection just below.
.. _`REGEX MATCHALL`:
@ -154,10 +170,12 @@ The following characters have special meaning in regular expressions:
Matches a pattern on either side of the ``|``
``()``
Saves a matched subexpression, which can be referenced
in the ``REGEX REPLACE`` operation. Additionally it is saved
by all regular expression-related commands, including
e.g. :command:`if(MATCHES)`, in the variables
:variable:`CMAKE_MATCH_<n>` for ``<n>`` 0..9.
in the ``REGEX REPLACE`` operation.
.. versionadded:: 3.9
All regular expression-related commands, including e.g.
:command:`if(MATCHES)`, save subgroup matches in the variables
:variable:`CMAKE_MATCH_<n>` for ``<n>`` 0..9.
``*``, ``+`` and ``?`` have higher precedence than concatenation. ``|``
has lower precedence than concatenation. This means that the regular
@ -189,6 +207,8 @@ Manipulation
string(APPEND <string_variable> [<input>...])
.. versionadded:: 3.4
Append all the ``<input>`` arguments to the string.
.. _PREPEND:
@ -197,6 +217,8 @@ Append all the ``<input>`` arguments to the string.
string(PREPEND <string_variable> [<input>...])
.. versionadded:: 3.10
Prepend all the ``<input>`` arguments to the string.
.. _CONCAT:
@ -214,6 +236,8 @@ the result in the named ``<output_variable>``.
string(JOIN <glue> <output_variable> [<input>...])
.. versionadded:: 3.12
Join all the ``<input>`` arguments together using the ``<glue>``
string and store the result in the named ``<output_variable>``.
@ -255,16 +279,15 @@ result stored in ``<output_variable>`` will *not* be the number of characters.
Store in an ``<output_variable>`` a substring of a given ``<string>``. If
``<length>`` is ``-1`` the remainder of the string starting at ``<begin>``
will be returned. If ``<string>`` is shorter than ``<length>`` then the
end of the string is used instead.
will be returned.
.. versionchanged:: 3.2
If ``<string>`` is shorter than ``<length>`` then the end of the string
is used instead. Previous versions of CMake reported an error in this case.
Both ``<begin>`` and ``<length>`` are counted in bytes, so care must
be exercised if ``<string>`` could contain multi-byte characters.
.. note::
CMake 3.1 and below reported an error if ``<length>`` pointed past
the end of ``<string>``.
.. _STRIP:
.. code-block:: cmake
@ -280,6 +303,8 @@ leading and trailing spaces removed.
string(GENEX_STRIP <string> <output_variable>)
.. versionadded:: 3.1
Strip any :manual:`generator expressions <cmake-generator-expressions(7)>`
from the input ``<string>`` and store the result in the ``<output_variable>``.
@ -289,6 +314,8 @@ from the input ``<string>`` and store the result in the ``<output_variable>``.
string(REPEAT <string> <count> <output_variable>)
.. versionadded:: 3.15
Produce the output string as the input ``<string>`` repeated ``<count>`` times.
Comparison
@ -307,6 +334,9 @@ Comparison
Compare the strings and store true or false in the ``<output_variable>``.
.. versionadded:: 3.7
Added the ``LESS_EQUAL`` and ``GREATER_EQUAL`` options.
.. _`Supported Hash Algorithms`:
Hashing
@ -342,6 +372,9 @@ The supported ``<HASH>`` algorithm names are:
``SHA3_512``
Keccak SHA-3.
.. versionadded:: 3.8
Added the ``SHA3_*`` hash algorithms.
Generation
^^^^^^^^^^
@ -353,6 +386,18 @@ Generation
Convert all numbers into corresponding ASCII characters.
.. _HEX:
.. code-block:: cmake
string(HEX <string> <output_variable>)
.. versionadded:: 3.18
Convert each byte in the input ``<string>`` to its hexadecimal representation
and store the concatenated hex digits in the ``<output_variable>``. Letters in
the output (``a`` through ``f``) are in lowercase.
.. _CONFIGURE:
.. code-block:: cmake
@ -404,26 +449,78 @@ be in Coordinated Universal Time (UTC) rather than local time.
The optional ``<format_string>`` may contain the following format
specifiers:
::
``%%``
.. versionadded:: 3.8
%% A literal percent sign (%).
%d The day of the current month (01-31).
%H The hour on a 24-hour clock (00-23).
%I The hour on a 12-hour clock (01-12).
%j The day of the current year (001-366).
%m The month of the current year (01-12).
%b Abbreviated month name (e.g. Oct).
%B Full month name (e.g. October).
%M The minute of the current hour (00-59).
%s Seconds since midnight (UTC) 1-Jan-1970 (UNIX time).
%S The second of the current minute.
60 represents a leap second. (00-60)
%U The week number of the current year (00-53).
%w The day of the current week. 0 is Sunday. (0-6)
%a Abbreviated weekday name (e.g. Fri).
%A Full weekday name (e.g. Friday).
%y The last two digits of the current year (00-99)
%Y The current year.
A literal percent sign (%).
``%d``
The day of the current month (01-31).
``%H``
The hour on a 24-hour clock (00-23).
``%I``
The hour on a 12-hour clock (01-12).
``%j``
The day of the current year (001-366).
``%m``
The month of the current year (01-12).
``%b``
.. versionadded:: 3.7
Abbreviated month name (e.g. Oct).
``%B``
.. versionadded:: 3.10
Full month name (e.g. October).
``%M``
The minute of the current hour (00-59).
``%s``
.. versionadded:: 3.6
Seconds since midnight (UTC) 1-Jan-1970 (UNIX time).
``%S``
The second of the current minute. 60 represents a leap second. (00-60)
``%f``
.. versionadded:: 3.23
The microsecond of the current second (000000-999999).
``%U``
The week number of the current year (00-53).
``%V``
.. versionadded:: 3.22
The ISO 8601 week number of the current year (01-53).
``%w``
The day of the current week. 0 is Sunday. (0-6)
``%a``
.. versionadded:: 3.7
Abbreviated weekday name (e.g. Fri).
``%A``
.. versionadded:: 3.10
Full weekday name (e.g. Friday).
``%y``
The last two digits of the current year (00-99).
``%Y``
The current year.
Unknown format specifiers will be ignored and copied to the output
as-is.
@ -435,8 +532,7 @@ If no explicit ``<format_string>`` is given, it will default to:
%Y-%m-%dT%H:%M:%S for local time.
%Y-%m-%dT%H:%M:%SZ for UTC.
.. note::
.. versionadded:: 3.8
If the ``SOURCE_DATE_EPOCH`` environment variable is set,
its value will be used instead of the current time.
See https://reproducible-builds.org/specs/source-date-epoch/ for details.
@ -448,6 +544,8 @@ If no explicit ``<format_string>`` is given, it will default to:
string(UUID <output_variable> NAMESPACE <namespace> NAME <name>
TYPE <MD5|SHA1> [UPPER])
.. versionadded:: 3.1
Create a universally unique identifier (aka GUID) as per RFC4122
based on the hash of the combined values of ``<namespace>``
(which itself has to be a valid UUID) and ``<name>``.
@ -457,3 +555,98 @@ A UUID has the format ``xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx``
where each ``x`` represents a lower case hexadecimal character.
Where required, an uppercase representation can be requested
with the optional ``UPPER`` flag.
.. _JSON:
JSON
^^^^
.. versionadded:: 3.19
Functionality for querying a JSON string.
.. note::
In each of the following JSON-related subcommands, if the optional
``ERROR_VARIABLE`` argument is given, errors will be reported in
``<error-variable>`` and the ``<out-var>`` will be set to
``<member|index>-[<member|index>...]-NOTFOUND`` with the path elements
up to the point where the error occurred, or just ``NOTFOUND`` if there
is no relevant path. If an error occurs but the ``ERROR_VARIABLE``
option is not present, a fatal error message is generated. If no error
occurs, the ``<error-variable>`` will be set to ``NOTFOUND``.
.. _GET:
.. code-block:: cmake
string(JSON <out-var> [ERROR_VARIABLE <error-variable>]
GET <json-string> <member|index> [<member|index> ...])
Get an element from ``<json-string>`` at the location given
by the list of ``<member|index>`` arguments.
Array and object elements will be returned as a JSON string.
Boolean elements will be returned as ``ON`` or ``OFF``.
Null elements will be returned as an empty string.
Number and string types will be returned as strings.
.. _TYPE:
.. code-block:: cmake
string(JSON <out-var> [ERROR_VARIABLE <error-variable>]
TYPE <json-string> <member|index> [<member|index> ...])
Get the type of an element in ``<json-string>`` at the location
given by the list of ``<member|index>`` arguments. The ``<out-var>``
will be set to one of ``NULL``, ``NUMBER``, ``STRING``, ``BOOLEAN``,
``ARRAY``, or ``OBJECT``.
.. _MEMBER:
.. code-block:: cmake
string(JSON <out-var> [ERROR_VARIABLE <error-var>]
MEMBER <json-string>
[<member|index> ...] <index>)
Get the name of the ``<index>``-th member in ``<json-string>`` at the location
given by the list of ``<member|index>`` arguments.
Requires an element of object type.
.. _JSONLENGTH:
.. code-block:: cmake
string(JSON <out-var> [ERROR_VARIABLE <error-variable>]
LENGTH <json-string> [<member|index> ...])
Get the length of an element in ``<json-string>`` at the location
given by the list of ``<member|index>`` arguments.
Requires an element of array or object type.
.. _REMOVE:
.. code-block:: cmake
string(JSON <out-var> [ERROR_VARIABLE <error-variable>]
REMOVE <json-string> <member|index> [<member|index> ...])
Remove an element from ``<json-string>`` at the location
given by the list of ``<member|index>`` arguments. The JSON string
without the removed element will be stored in ``<out-var>``.
.. _SET:
.. code-block:: cmake
string(JSON <out-var> [ERROR_VARIABLE <error-variable>]
SET <json-string> <member|index> [<member|index> ...] <value>)
Set an element in ``<json-string>`` at the location
given by the list of ``<member|index>`` arguments to ``<value>``.
The contents of ``<value>`` should be valid JSON.
.. _EQUAL:
.. code-block:: cmake
string(JSON <out-var> [ERROR_VARIABLE <error-var>]
EQUAL <json-string1> <json-string2>)
Compare the two JSON objects given by ``<json-string1>`` and ``<json-string2>``
for equality. The contents of ``<json-string1>`` and ``<json-string2>``
should be valid JSON. The ``<out-var>`` will be set to a true value if the
JSON objects are considered equal, or a false value otherwise.

View File

@ -15,14 +15,16 @@ named ``<target>`` must have been created by a command such as
:ref:`ALIAS target <Alias Targets>`.
The ``INTERFACE``, ``PUBLIC`` and ``PRIVATE`` keywords are required to
specify the scope of the following arguments. ``PRIVATE`` and ``PUBLIC``
items will populate the :prop_tgt:`COMPILE_DEFINITIONS` property of
``<target>``. ``PUBLIC`` and ``INTERFACE`` items will populate the
specify the :ref:`scope <Target Usage Requirements>` of the following arguments.
``PRIVATE`` and ``PUBLIC`` items will populate the :prop_tgt:`COMPILE_DEFINITIONS`
property of ``<target>``. ``PUBLIC`` and ``INTERFACE`` items will populate the
:prop_tgt:`INTERFACE_COMPILE_DEFINITIONS` property of ``<target>``.
(:ref:`IMPORTED targets <Imported Targets>` only support ``INTERFACE`` items.)
The following arguments specify compile definitions. Repeated calls for the
same ``<target>`` append items in the order called.
.. versionadded:: 3.11
Allow setting ``INTERFACE`` items on :ref:`IMPORTED targets <Imported Targets>`.
Arguments to ``target_compile_definitions`` may use "generator expressions"
with the syntax ``$<...>``. See the :manual:`cmake-generator-expressions(7)`
manual for available expressions. See the :manual:`cmake-buildsystem(7)`
@ -37,3 +39,12 @@ For example, the following are all equivalent:
target_compile_definitions(foo PUBLIC -DFOO) # -D removed
target_compile_definitions(foo PUBLIC "" FOO) # "" ignored
target_compile_definitions(foo PUBLIC -D FOO) # -D becomes "", then ignored
Definitions may optionally have values:
.. code-block:: cmake
target_compile_definitions(foo PUBLIC FOO=1)
Note that many compilers treat ``-DFOO`` as equivalent to ``-DFOO=1``, but
other tools may not recognize this in all circumstances (e.g. IntelliSense).

Some files were not shown because too many files have changed in this diff Show More