cmake_language.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. cmake_language
  2. --------------
  3. .. versionadded:: 3.18
  4. Call meta-operations on CMake commands.
  5. Synopsis
  6. ^^^^^^^^
  7. .. parsed-literal::
  8. cmake_language(`CALL`_ <command> [<arg>...])
  9. cmake_language(`EVAL`_ CODE <code>...)
  10. cmake_language(`DEFER`_ <options>... CALL <command> [<arg>...])
  11. cmake_language(`SET_DEPENDENCY_PROVIDER`_ <command> SUPPORTED_METHODS <methods>...)
  12. cmake_language(`GET_MESSAGE_LOG_LEVEL`_ <out-var>)
  13. cmake_language(`EXIT`_ <exit-code>)
  14. cmake_language(`TRACE`_ <boolean> ...)
  15. Introduction
  16. ^^^^^^^^^^^^
  17. This command will call meta-operations on built-in CMake commands or
  18. those created via the :command:`macro` or :command:`function` commands.
  19. ``cmake_language`` does not introduce a new variable or policy scope.
  20. Calling Commands
  21. ^^^^^^^^^^^^^^^^
  22. .. signature::
  23. cmake_language(CALL <command> [<arg>...])
  24. Calls the named ``<command>`` with the given arguments (if any).
  25. For example, the code:
  26. .. code-block:: cmake
  27. set(message_command "message")
  28. cmake_language(CALL ${message_command} STATUS "Hello World!")
  29. is equivalent to
  30. .. code-block:: cmake
  31. message(STATUS "Hello World!")
  32. .. note::
  33. To ensure consistency of the code, the following commands are not allowed:
  34. * ``if`` / ``elseif`` / ``else`` / ``endif``
  35. * ``block`` / ``endblock``
  36. * ``while`` / ``endwhile``
  37. * ``foreach`` / ``endforeach``
  38. * ``function`` / ``endfunction``
  39. * ``macro`` / ``endmacro``
  40. Evaluating Code
  41. ^^^^^^^^^^^^^^^
  42. .. signature::
  43. cmake_language(EVAL CODE <code>...)
  44. :target: EVAL
  45. Evaluates the ``<code>...`` as CMake code.
  46. For example, the code:
  47. .. code-block:: cmake
  48. set(A TRUE)
  49. set(B TRUE)
  50. set(C TRUE)
  51. set(condition "(A AND B) OR C")
  52. cmake_language(EVAL CODE "
  53. if (${condition})
  54. message(STATUS TRUE)
  55. else()
  56. message(STATUS FALSE)
  57. endif()"
  58. )
  59. is equivalent to
  60. .. code-block:: cmake
  61. set(A TRUE)
  62. set(B TRUE)
  63. set(C TRUE)
  64. set(condition "(A AND B) OR C")
  65. file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/eval.cmake "
  66. if (${condition})
  67. message(STATUS TRUE)
  68. else()
  69. message(STATUS FALSE)
  70. endif()"
  71. )
  72. include(${CMAKE_CURRENT_BINARY_DIR}/eval.cmake)
  73. Deferring Calls
  74. ^^^^^^^^^^^^^^^
  75. .. versionadded:: 3.19
  76. .. signature::
  77. cmake_language(DEFER <options>... CALL <command> [<arg>...])
  78. Schedules a call to the named ``<command>`` with the given arguments (if any)
  79. to occur at a later time. By default, deferred calls are executed as if
  80. written at the end of the current directory's ``CMakeLists.txt`` file,
  81. except that they run even after a :command:`return` call. Variable
  82. references in arguments are evaluated at the time the deferred call is
  83. executed.
  84. The options are:
  85. ``DIRECTORY <dir>``
  86. Schedule the call for the end of the given directory instead of the
  87. current directory. The ``<dir>`` may reference either a source
  88. directory or its corresponding binary directory. Relative paths are
  89. treated as relative to the current source directory.
  90. The given directory must be known to CMake, being either the top-level
  91. directory or one added by :command:`add_subdirectory`. Furthermore,
  92. the given directory must not yet be finished processing. This means
  93. it can be the current directory or one of its ancestors.
  94. ``ID <id>``
  95. Specify an identification for the deferred call.
  96. The ``<id>`` may not be empty and may not begin with a capital letter ``A-Z``.
  97. The ``<id>`` may begin with an underscore (``_``) only if it was generated
  98. automatically by an earlier call that used ``ID_VAR`` to get the id.
  99. ``ID_VAR <var>``
  100. Specify a variable in which to store the identification for the
  101. deferred call. If ``ID <id>`` is not given, a new identification
  102. will be generated and the generated id will start with an underscore (``_``).
  103. The currently scheduled list of deferred calls may be retrieved:
  104. .. code-block:: cmake
  105. cmake_language(DEFER [DIRECTORY <dir>] GET_CALL_IDS <var>)
  106. This will store in ``<var>`` a :ref:`semicolon-separated list <CMake Language
  107. Lists>` of deferred call ids. The ids are for the directory scope in which
  108. the calls have been deferred to (i.e. where they will be executed), which can
  109. be different to the scope in which they were created. The ``DIRECTORY``
  110. option can be used to specify the scope for which to retrieve the call ids.
  111. If that option is not given, the call ids for the current directory scope
  112. will be returned.
  113. Details of a specific call may be retrieved from its id:
  114. .. code-block:: cmake
  115. cmake_language(DEFER [DIRECTORY <dir>] GET_CALL <id> <var>)
  116. This will store in ``<var>`` a :ref:`semicolon-separated list <CMake Language
  117. Lists>` in which the first element is the name of the command to be
  118. called, and the remaining elements are its unevaluated arguments (any
  119. contained ``;`` characters are included literally and cannot be distinguished
  120. from multiple arguments). If multiple calls are scheduled with the same id,
  121. this retrieves the first one. If no call is scheduled with the given id in
  122. the specified ``DIRECTORY`` scope (or the current directory scope if no
  123. ``DIRECTORY`` option is given), this stores an empty string in the variable.
  124. Deferred calls may be canceled by their id:
  125. .. code-block:: cmake
  126. cmake_language(DEFER [DIRECTORY <dir>] CANCEL_CALL <id>...)
  127. This cancels all deferred calls matching any of the given ids in the specified
  128. ``DIRECTORY`` scope (or the current directory scope if no ``DIRECTORY`` option
  129. is given). Unknown ids are silently ignored.
  130. Deferred Call Examples
  131. """"""""""""""""""""""
  132. For example, the code:
  133. .. code-block:: cmake
  134. cmake_language(DEFER CALL message "${deferred_message}")
  135. cmake_language(DEFER ID_VAR id CALL message "Canceled Message")
  136. cmake_language(DEFER CANCEL_CALL ${id})
  137. message("Immediate Message")
  138. set(deferred_message "Deferred Message")
  139. prints::
  140. Immediate Message
  141. Deferred Message
  142. The ``Canceled Message`` is never printed because its command is
  143. canceled. The ``deferred_message`` variable reference is not evaluated
  144. until the call site, so it can be set after the deferred call is scheduled.
  145. In order to evaluate variable references immediately when scheduling a
  146. deferred call, wrap it using ``cmake_language(EVAL)``. However, note that
  147. arguments will be re-evaluated in the deferred call, though that can be
  148. avoided by using bracket arguments. For example:
  149. .. code-block:: cmake
  150. set(deferred_message "Deferred Message 1")
  151. set(re_evaluated [[${deferred_message}]])
  152. cmake_language(EVAL CODE "
  153. cmake_language(DEFER CALL message [[${deferred_message}]])
  154. cmake_language(DEFER CALL message \"${re_evaluated}\")
  155. ")
  156. message("Immediate Message")
  157. set(deferred_message "Deferred Message 2")
  158. also prints::
  159. Immediate Message
  160. Deferred Message 1
  161. Deferred Message 2
  162. .. _dependency_providers:
  163. Dependency Providers
  164. ^^^^^^^^^^^^^^^^^^^^
  165. .. versionadded:: 3.24
  166. .. note:: A high-level introduction to this feature can be found in the
  167. :ref:`Using Dependencies Guide <dependency_providers_overview>`.
  168. .. signature::
  169. cmake_language(SET_DEPENDENCY_PROVIDER <command>
  170. SUPPORTED_METHODS <methods>...)
  171. When a call is made to :command:`find_package` or
  172. :command:`FetchContent_MakeAvailable`, the call may be forwarded to a
  173. dependency provider which then has the opportunity to fulfill the request.
  174. If the request is for one of the ``<methods>`` specified when the provider
  175. was set, CMake calls the provider's ``<command>`` with a set of
  176. method-specific arguments. If the provider does not fulfill the request,
  177. or if the provider doesn't support the request's method, or no provider
  178. is set, the built-in :command:`find_package` or
  179. :command:`FetchContent_MakeAvailable` implementation is used to fulfill
  180. the request in the usual way.
  181. One or more of the following values can be specified for the ``<methods>``
  182. when setting the provider:
  183. ``FIND_PACKAGE``
  184. The provider command accepts :command:`find_package` requests.
  185. ``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
  186. The provider command accepts :command:`FetchContent_MakeAvailable`
  187. requests. It expects each dependency to be fed to the provider command
  188. one at a time, not the whole list in one go.
  189. Only one provider can be set at any point in time. If a provider is already
  190. set when ``cmake_language(SET_DEPENDENCY_PROVIDER)`` is called, the new
  191. provider replaces the previously set one. The specified ``<command>`` must
  192. already exist when ``cmake_language(SET_DEPENDENCY_PROVIDER)`` is called.
  193. As a special case, providing an empty string for the ``<command>`` and no
  194. ``<methods>`` will discard any previously set provider.
  195. The dependency provider can only be set while processing one of the files
  196. specified by the :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable.
  197. Thus, dependency providers can only be set as part of the first call to
  198. :command:`project`. Calling ``cmake_language(SET_DEPENDENCY_PROVIDER)``
  199. outside of that context will result in an error.
  200. .. versionadded:: 3.30
  201. The :prop_gbl:`PROPAGATE_TOP_LEVEL_INCLUDES_TO_TRY_COMPILE` global
  202. property can be set if the dependency provider also wants to be enabled
  203. in whole-project calls to :command:`try_compile`.
  204. .. note::
  205. The choice of dependency provider should always be under the user's control.
  206. As a convenience, a project may choose to provide a file that users can
  207. list in their :variable:`CMAKE_PROJECT_TOP_LEVEL_INCLUDES` variable, but
  208. the use of such a file should always be the user's choice.
  209. Provider commands
  210. """""""""""""""""
  211. Providers define a single ``<command>`` to accept requests. The name of
  212. the command should be specific to that provider, not something overly
  213. generic that another provider might also use. This enables users to compose
  214. different providers in their own custom provider. The recommended form is
  215. ``xxx_provide_dependency()``, where ``xxx`` is the provider-specific part
  216. (e.g. ``vcpkg_provide_dependency()``, ``conan_provide_dependency()``,
  217. ``ourcompany_provide_dependency()``, and so on).
  218. .. code-block:: cmake
  219. xxx_provide_dependency(<method> [<method-specific-args>...])
  220. Because some methods expect certain variables to be set in the calling scope,
  221. the provider command should typically be implemented as a macro rather than a
  222. function. This ensures it does not introduce a new variable scope.
  223. The arguments CMake passes to the dependency provider depend on the type of
  224. request. The first argument is always the method, and it will only ever
  225. be one of the ``<methods>`` that was specified when setting the provider.
  226. ``FIND_PACKAGE``
  227. The ``<method-specific-args>`` will be everything passed to the
  228. :command:`find_package` call that requested the dependency. The first of
  229. these ``<method-specific-args>`` will therefore always be the name of the
  230. dependency. Dependency names are case-sensitive for this method because
  231. :command:`find_package` treats them case-sensitively too.
  232. If the provider command fulfills the request, it must set the same variable
  233. that :command:`find_package` expects to be set. For a dependency named
  234. ``depName``, the provider must set ``depName_FOUND`` to true if it fulfilled
  235. the request. If the provider returns without setting this variable, CMake
  236. will assume the request was not fulfilled and will fall back to the
  237. built-in implementation.
  238. If the provider needs to call the built-in :command:`find_package`
  239. implementation as part of its processing, it can do so by including the
  240. ``BYPASS_PROVIDER`` keyword as one of the arguments.
  241. ``FETCHCONTENT_MAKEAVAILABLE_SERIAL``
  242. The ``<method-specific-args>`` will be everything passed to the
  243. :command:`FetchContent_Declare` call that corresponds to the requested
  244. dependency, with the following exceptions:
  245. * If ``SOURCE_DIR`` or ``BINARY_DIR`` were not part of the original
  246. declared arguments, they will be added with their default values.
  247. * If :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE` is set to ``NEVER``,
  248. any ``FIND_PACKAGE_ARGS`` will be omitted.
  249. * The ``OVERRIDE_FIND_PACKAGE`` keyword is always omitted.
  250. The first of the ``<method-specific-args>`` will always be the name of the
  251. dependency. Dependency names are case-insensitive for this method because
  252. :module:`FetchContent` also treats them case-insensitively.
  253. If the provider fulfills the request, it should call
  254. :command:`FetchContent_SetPopulated`, passing the name of the dependency as
  255. the first argument. The ``SOURCE_DIR`` and ``BINARY_DIR`` arguments to that
  256. command should only be given if the provider makes the dependency's source
  257. and build directories available in exactly the same way as the built-in
  258. :command:`FetchContent_MakeAvailable` command.
  259. If the provider returns without calling :command:`FetchContent_SetPopulated`
  260. for the named dependency, CMake will assume the request was not fulfilled
  261. and will fall back to the built-in implementation.
  262. Note that empty arguments may be significant for this method (e.g. an empty
  263. string following a ``GIT_SUBMODULES`` keyword). Therefore, if forwarding
  264. these arguments on to another command, extra care must be taken to avoid such
  265. arguments being silently dropped.
  266. If ``FETCHCONTENT_SOURCE_DIR_<uppercaseDepName>`` is set, then the
  267. dependency provider will never see requests for the ``<depName>`` dependency
  268. for this method. When the user sets such a variable, they are explicitly
  269. overriding where to get that dependency from and are taking on the
  270. responsibility that their overriding version meets any requirements for that
  271. dependency and is compatible with whatever else in the project uses it.
  272. Depending on the value of :variable:`FETCHCONTENT_TRY_FIND_PACKAGE_MODE`
  273. and whether the ``OVERRIDE_FIND_PACKAGE`` option was given to
  274. :command:`FetchContent_Declare`, having
  275. ``FETCHCONTENT_SOURCE_DIR_<uppercaseDepName>`` set may also prevent the
  276. dependency provider from seeing requests for a ``find_package(depName)``
  277. call too.
  278. Provider Examples
  279. """""""""""""""""
  280. This first example only intercepts :command:`find_package` calls. The
  281. provider command runs an external tool which copies the relevant artifacts
  282. into a provider-specific directory, if that tool knows about the dependency.
  283. It then relies on the built-in implementation to then find those artifacts.
  284. :command:`FetchContent_MakeAvailable` calls would not go through the provider.
  285. .. code-block:: cmake
  286. :caption: mycomp_provider.cmake
  287. # Always ensure we have the policy settings this provider expects
  288. cmake_minimum_required(VERSION 3.24)
  289. set(MYCOMP_PROVIDER_INSTALL_DIR ${CMAKE_BINARY_DIR}/mycomp_packages
  290. CACHE PATH "The directory this provider installs packages to"
  291. )
  292. # Tell the built-in implementation to look in our area first, unless
  293. # the find_package() call uses NO_..._PATH options to exclude it
  294. list(APPEND CMAKE_MODULE_PATH ${MYCOMP_PROVIDER_INSTALL_DIR}/cmake)
  295. list(APPEND CMAKE_PREFIX_PATH ${MYCOMP_PROVIDER_INSTALL_DIR})
  296. macro(mycomp_provide_dependency method package_name)
  297. execute_process(
  298. COMMAND some_tool ${package_name} --installdir ${MYCOMP_PROVIDER_INSTALL_DIR}
  299. COMMAND_ERROR_IS_FATAL ANY
  300. )
  301. endmacro()
  302. cmake_language(
  303. SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
  304. SUPPORTED_METHODS FIND_PACKAGE
  305. )
  306. The user would then typically use the above file like so::
  307. cmake -DCMAKE_PROJECT_TOP_LEVEL_INCLUDES=/path/to/mycomp_provider.cmake ...
  308. The next example demonstrates a provider that accepts both methods, but
  309. only handles one specific dependency. It enforces providing Google Test
  310. using :module:`FetchContent`, but leaves all other dependencies to be
  311. fulfilled by CMake's built-in implementation. It accepts a few different
  312. names, which demonstrates one way of working around projects that hard-code
  313. an unusual or undesirable way of adding this particular dependency to the
  314. build. The example also demonstrates how to use the :command:`list` command
  315. to preserve variables that may be overwritten by a call to
  316. :command:`FetchContent_MakeAvailable`.
  317. .. code-block:: cmake
  318. :caption: mycomp_provider.cmake
  319. cmake_minimum_required(VERSION 3.24)
  320. # Because we declare this very early, it will take precedence over any
  321. # details the project might declare later for the same thing
  322. include(FetchContent)
  323. FetchContent_Declare(
  324. googletest
  325. GIT_REPOSITORY https://github.com/google/googletest.git
  326. GIT_TAG e2239ee6043f73722e7aa812a459f54a28552929 # release-1.11.0
  327. )
  328. # Both FIND_PACKAGE and FETCHCONTENT_MAKEAVAILABLE_SERIAL methods provide
  329. # the package or dependency name as the first method-specific argument.
  330. macro(mycomp_provide_dependency method dep_name)
  331. if("${dep_name}" MATCHES "^(gtest|googletest)$")
  332. # Save our current command arguments in case we are called recursively
  333. list(APPEND mycomp_provider_args ${method} ${dep_name})
  334. # This will forward to the built-in FetchContent implementation,
  335. # which detects a recursive call for the same thing and avoids calling
  336. # the provider again if dep_name is the same as the current call.
  337. FetchContent_MakeAvailable(googletest)
  338. # Restore our command arguments
  339. list(POP_BACK mycomp_provider_args dep_name method)
  340. # Tell the caller we fulfilled the request
  341. if("${method}" STREQUAL "FIND_PACKAGE")
  342. # We need to set this if we got here from a find_package() call
  343. # since we used a different method to fulfill the request.
  344. # This example assumes projects only use the gtest targets,
  345. # not any of the variables the FindGTest module may define.
  346. set(${dep_name}_FOUND TRUE)
  347. elseif(NOT "${dep_name}" STREQUAL "googletest")
  348. # We used the same method, but were given a different name to the
  349. # one we populated with. Tell the caller about the name it used.
  350. FetchContent_SetPopulated(${dep_name}
  351. SOURCE_DIR "${googletest_SOURCE_DIR}"
  352. BINARY_DIR "${googletest_BINARY_DIR}"
  353. )
  354. endif()
  355. endif()
  356. endmacro()
  357. cmake_language(
  358. SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
  359. SUPPORTED_METHODS
  360. FIND_PACKAGE
  361. FETCHCONTENT_MAKEAVAILABLE_SERIAL
  362. )
  363. The final example demonstrates how to modify arguments to a
  364. :command:`find_package` call. It forces all such calls to have the
  365. ``QUIET`` keyword. It uses the ``BYPASS_PROVIDER`` keyword to prevent
  366. calling the provider command recursively for the same dependency.
  367. .. code-block:: cmake
  368. :caption: mycomp_provider.cmake
  369. cmake_minimum_required(VERSION 3.24)
  370. macro(mycomp_provide_dependency method)
  371. find_package(${ARGN} BYPASS_PROVIDER QUIET)
  372. endmacro()
  373. cmake_language(
  374. SET_DEPENDENCY_PROVIDER mycomp_provide_dependency
  375. SUPPORTED_METHODS FIND_PACKAGE
  376. )
  377. Getting current message log level
  378. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  379. .. versionadded:: 3.25
  380. .. _query_message_log_level:
  381. .. signature::
  382. cmake_language(GET_MESSAGE_LOG_LEVEL <output_variable>)
  383. Writes the current :command:`message` logging level
  384. into the given ``<output_variable>``.
  385. See :command:`message` for the possible logging levels.
  386. The current message logging level can be set either using the
  387. :option:`--log-level <cmake --log-level>`
  388. command line option of the :manual:`cmake(1)` program or using
  389. the :variable:`CMAKE_MESSAGE_LOG_LEVEL` variable.
  390. If both the command line option and the variable are set, the command line
  391. option takes precedence. If neither are set, the default logging level
  392. is returned.
  393. Terminating Scripts
  394. ^^^^^^^^^^^^^^^^^^^
  395. .. versionadded:: 3.29
  396. .. signature::
  397. cmake_language(EXIT <exit-code>)
  398. Terminate the current :option:`cmake -P` script and exit with ``<exit-code>``.
  399. This command works only in :ref:`script mode <Script Processing Mode>`.
  400. If used outside of that context, it will cause a fatal error.
  401. The ``<exit-code>`` should be non-negative.
  402. If ``<exit-code>`` is negative, then the behavior
  403. is unspecified (e.g., on Windows the error code -1
  404. becomes ``0xffffffff``, and on Linux it becomes 255).
  405. Exit codes above 255 may not be supported by the underlying
  406. shell or platform, and some shells may interpret values
  407. above 125 specially. Therefore, it is advisable to only
  408. specify an ``<exit-code>`` in the range 0 to 125.
  409. .. _trace:
  410. Trace Control
  411. ^^^^^^^^^^^^^
  412. .. versionadded:: 4.2
  413. .. signature::
  414. cmake_language(TRACE ON [EXPAND])
  415. cmake_language(TRACE OFF)
  416. The TRACE subcommand controls runtime tracing of executed CMake commands and
  417. macros within the current process. When enabled, trace output is written
  418. in the same format as if CMake had been started with the
  419. :option:`cmake --trace` or :option:`cmake --trace-expand` command line options.
  420. Tracing scopes are nestable. Multiple ``TRACE ON`` calls may be active at the
  421. same time, and each ``TRACE OFF`` deactivates one nesting level.
  422. If CMake is run with :option:`cmake --trace` or :option:`cmake --trace-expand`,
  423. those options override and force tracing globally, regardless of
  424. ``cmake_language(TRACE OFF)`` calls. In such cases, the command may still
  425. be invoked but has no effect on the trace state.