1.. cmake-manual-description: CMake Developer Reference
2
3cmake-developer(7)
4******************
5
6.. only:: html
7
8   .. contents::
9
10Introduction
11============
12
13This manual is intended for reference by developers working with
14:manual:`cmake-language(7)` code, whether writing their own modules,
15authoring their own build systems, or working on CMake itself.
16
17See https://cmake.org/get-involved/ to get involved in development of
18CMake upstream.  It includes links to contribution instructions, which
19in turn link to developer guides for CMake itself.
20
21.. _`Find Modules`:
22
23Find Modules
24============
25
26A "find module" is a ``Find<PackageName>.cmake`` file to be loaded by the
27:command:`find_package` command when invoked for ``<PackageName>``.
28
29The primary task of a find module is to determine whether a package is
30available, set the ``<PackageName>_FOUND`` variable to reflect this and
31provide any variables, macros and imported targets required to use the
32package.  A find module is useful in cases where an upstream library does
33not provide a :ref:`config file package <Config File Packages>`.
34
35The traditional approach is to use variables for everything, including
36libraries and executables: see the `Standard Variable Names`_ section
37below.  This is what most of the existing find modules provided by CMake
38do.
39
40The more modern approach is to behave as much like
41:ref:`config file packages <Config File Packages>` files as possible, by
42providing :ref:`imported target <Imported targets>`.  This has the advantage
43of propagating :ref:`Target Usage Requirements` to consumers.
44
45In either case (or even when providing both variables and imported
46targets), find modules should provide backwards compatibility with old
47versions that had the same name.
48
49A FindFoo.cmake module will typically be loaded by the command::
50
51  find_package(Foo [major[.minor[.patch[.tweak]]]]
52               [EXACT] [QUIET] [REQUIRED]
53               [[COMPONENTS] [components...]]
54               [OPTIONAL_COMPONENTS components...]
55               [NO_POLICY_SCOPE])
56
57See the :command:`find_package` documentation for details on what
58variables are set for the find module.  Most of these are dealt with by
59using :module:`FindPackageHandleStandardArgs`.
60
61Briefly, the module should only locate versions of the package
62compatible with the requested version, as described by the
63``Foo_FIND_VERSION`` family of variables.  If ``Foo_FIND_QUIETLY`` is
64set to true, it should avoid printing messages, including anything
65complaining about the package not being found.  If ``Foo_FIND_REQUIRED``
66is set to true, the module should issue a ``FATAL_ERROR`` if the package
67cannot be found.  If neither are set to true, it should print a
68non-fatal message if it cannot find the package.
69
70Packages that find multiple semi-independent parts (like bundles of
71libraries) should search for the components listed in
72``Foo_FIND_COMPONENTS`` if it is set , and only set ``Foo_FOUND`` to
73true if for each searched-for component ``<c>`` that was not found,
74``Foo_FIND_REQUIRED_<c>`` is not set to true.  The ``HANDLE_COMPONENTS``
75argument of ``find_package_handle_standard_args()`` can be used to
76implement this.
77
78If ``Foo_FIND_COMPONENTS`` is not set, which modules are searched for
79and required is up to the find module, but should be documented.
80
81For internal implementation, it is a generally accepted convention that
82variables starting with underscore are for temporary use only.
83
84
85.. _`CMake Developer Standard Variable Names`:
86
87Standard Variable Names
88-----------------------
89
90For a ``FindXxx.cmake`` module that takes the approach of setting
91variables (either instead of or in addition to creating imported
92targets), the following variable names should be used to keep things
93consistent between Find modules.  Note that all variables start with
94``Xxx_``, which (unless otherwise noted) must match exactly the name
95of the ``FindXxx.cmake`` file, including upper/lowercase.
96This prefix on the variable names ensures that they do not conflict with
97variables of other Find modules.  The same pattern should also be followed
98for any macros, functions and imported targets defined by the Find module.
99
100``Xxx_INCLUDE_DIRS``
101  The final set of include directories listed in one variable for use by
102  client code. This should not be a cache entry (note that this also means
103  this variable should not be used as the result variable of a
104  :command:`find_path` command - see ``Xxx_INCLUDE_DIR`` below for that).
105
106``Xxx_LIBRARIES``
107  The libraries to use with the module.  These may be CMake targets, full
108  absolute paths to a library binary or the name of a library that the
109  linker must find in its search path.  This should not be a cache entry
110  (note that this also means this variable should not be used as the
111  result variable of a :command:`find_library` command - see
112  ``Xxx_LIBRARY`` below for that).
113
114``Xxx_DEFINITIONS``
115  The compile definitions to use when compiling code that uses the module.
116  This really shouldn't include options such as ``-DHAS_JPEG`` that a client
117  source-code file uses to decide whether to ``#include <jpeg.h>``
118
119``Xxx_EXECUTABLE``
120  The full absolute path to an executable.  In this case, ``Xxx`` might not
121  be the name of the module, it might be the name of the tool (usually
122  converted to all uppercase), assuming that tool has such a well-known name
123  that it is unlikely that another tool with the same name exists.  It would
124  be appropriate to use this as the result variable of a
125  :command:`find_program` command.
126
127``Xxx_YYY_EXECUTABLE``
128  Similar to ``Xxx_EXECUTABLE`` except here the ``Xxx`` is always the module
129  name and ``YYY`` is the tool name (again, usually fully uppercase).
130  Prefer this form if the tool name is not very widely known or has the
131  potential  to clash with another tool.  For greater consistency, also
132  prefer this form if the module provides more than one executable.
133
134``Xxx_LIBRARY_DIRS``
135  Optionally, the final set of library directories listed in one
136  variable for use by client code. This should not be a cache entry.
137
138``Xxx_ROOT_DIR``
139  Where to find the base directory of the module.
140
141``Xxx_VERSION_VV``
142  Variables of this form specify whether the ``Xxx`` module being provided
143  is version ``VV`` of the module.  There should not be more than one
144  variable of this form set to true for a given module.  For example, a
145  module ``Barry`` might have evolved over many years and gone through a
146  number of different major versions.  Version 3 of the ``Barry`` module
147  might set the variable ``Barry_VERSION_3`` to true, whereas an older
148  version of the module might set ``Barry_VERSION_2`` to true instead.
149  It would be an error for both ``Barry_VERSION_3`` and ``Barry_VERSION_2``
150  to both be set to true.
151
152``Xxx_WRAP_YY``
153  When a variable of this form is set to false, it indicates that the
154  relevant wrapping command should not be used.  The wrapping command
155  depends on the module, it may be implied by the module name or it might
156  be specified by the ``YY`` part of the variable.
157
158``Xxx_Yy_FOUND``
159  For variables of this form, ``Yy`` is the name of a component for the
160  module.  It should match exactly one of the valid component names that
161  may be passed to the :command:`find_package` command for the module.
162  If a variable of this form is set to false, it means that the ``Yy``
163  component of module ``Xxx`` was not found or is not available.
164  Variables of this form would typically be used for optional components
165  so that the caller can check whether an optional component is available.
166
167``Xxx_FOUND``
168  When the :command:`find_package` command returns to the caller, this
169  variable will be set to true if the module was deemed to have been found
170  successfully.
171
172``Xxx_NOT_FOUND_MESSAGE``
173  Should be set by config-files in the case that it has set
174  ``Xxx_FOUND`` to FALSE.  The contained message will be printed by the
175  :command:`find_package` command and by
176  :command:`find_package_handle_standard_args` to inform the user about the
177  problem.  Use this instead of calling :command:`message` directly to
178  report a reason for failing to find the module or package.
179
180``Xxx_RUNTIME_LIBRARY_DIRS``
181  Optionally, the runtime library search path for use when running an
182  executable linked to shared libraries.  The list should be used by
183  user code to create the ``PATH`` on windows or ``LD_LIBRARY_PATH`` on
184  UNIX.  This should not be a cache entry.
185
186``Xxx_VERSION``
187  The full version string of the package found, if any.  Note that many
188  existing modules provide ``Xxx_VERSION_STRING`` instead.
189
190``Xxx_VERSION_MAJOR``
191  The major version of the package found, if any.
192
193``Xxx_VERSION_MINOR``
194  The minor version of the package found, if any.
195
196``Xxx_VERSION_PATCH``
197  The patch version of the package found, if any.
198
199The following names should not usually be used in ``CMakeLists.txt`` files.
200They are intended for use by Find modules to specify and cache the locations
201of specific files or directories.  Users are typically able to set and edit
202these variables to control the behavior of Find modules (like entering the
203path to a library manually):
204
205``Xxx_LIBRARY``
206  The path of the library.  Use this form only when the module provides a
207  single library.  It is appropriate to use this as the result variable
208  in a :command:`find_library` command.
209
210``Xxx_Yy_LIBRARY``
211  The path of library ``Yy`` provided by the module ``Xxx``.  Use this form
212  when the module provides more than one library or where other modules may
213  also provide a library of the same name. It is also appropriate to use
214  this form as the result variable in a :command:`find_library` command.
215
216``Xxx_INCLUDE_DIR``
217  When the module provides only a single library, this variable can be used
218  to specify where to find headers for using the library (or more accurately,
219  the path that consumers of the library should add to their header search
220  path).  It would be appropriate to use this as the result variable in a
221  :command:`find_path` command.
222
223``Xxx_Yy_INCLUDE_DIR``
224  If the module provides more than one library or where other modules may
225  also provide a library of the same name, this form is recommended for
226  specifying where to find headers for using library ``Yy`` provided by
227  the module.  Again, it would be appropriate to use this as the result
228  variable in a :command:`find_path` command.
229
230To prevent users being overwhelmed with settings to configure, try to
231keep as many options as possible out of the cache, leaving at least one
232option which can be used to disable use of the module, or locate a
233not-found library (e.g. ``Xxx_ROOT_DIR``).  For the same reason, mark
234most cache options as advanced.  For packages which provide both debug
235and release binaries, it is common to create cache variables with a
236``_LIBRARY_<CONFIG>`` suffix, such as ``Foo_LIBRARY_RELEASE`` and
237``Foo_LIBRARY_DEBUG``.  The :module:`SelectLibraryConfigurations` module
238can be helpful for such cases.
239
240While these are the standard variable names, you should provide
241backwards compatibility for any old names that were actually in use.
242Make sure you comment them as deprecated, so that no-one starts using
243them.
244
245
246A Sample Find Module
247--------------------
248
249We will describe how to create a simple find module for a library ``Foo``.
250
251The top of the module should begin with a license notice, followed by
252a blank line, and then followed by a :ref:`Bracket Comment`.  The comment
253should begin with ``.rst:`` to indicate that the rest of its content is
254reStructuredText-format documentation.  For example:
255
256::
257
258  # Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
259  # file Copyright.txt or https://cmake.org/licensing for details.
260
261  #[=======================================================================[.rst:
262  FindFoo
263  -------
264
265  Finds the Foo library.
266
267  Imported Targets
268  ^^^^^^^^^^^^^^^^
269
270  This module provides the following imported targets, if found:
271
272  ``Foo::Foo``
273    The Foo library
274
275  Result Variables
276  ^^^^^^^^^^^^^^^^
277
278  This will define the following variables:
279
280  ``Foo_FOUND``
281    True if the system has the Foo library.
282  ``Foo_VERSION``
283    The version of the Foo library which was found.
284  ``Foo_INCLUDE_DIRS``
285    Include directories needed to use Foo.
286  ``Foo_LIBRARIES``
287    Libraries needed to link to Foo.
288
289  Cache Variables
290  ^^^^^^^^^^^^^^^
291
292  The following cache variables may also be set:
293
294  ``Foo_INCLUDE_DIR``
295    The directory containing ``foo.h``.
296  ``Foo_LIBRARY``
297    The path to the Foo library.
298
299  #]=======================================================================]
300
301The module documentation consists of:
302
303* An underlined heading specifying the module name.
304
305* A simple description of what the module finds.
306  More description may be required for some packages.  If there are
307  caveats or other details users of the module should be aware of,
308  specify them here.
309
310* A section listing imported targets provided by the module, if any.
311
312* A section listing result variables provided by the module.
313
314* Optionally a section listing cache variables used by the module, if any.
315
316If the package provides any macros or functions, they should be listed in
317an additional section, but can be documented by additional ``.rst:``
318comment blocks immediately above where those macros or functions are defined.
319
320The find module implementation may begin below the documentation block.
321Now the actual libraries and so on have to be found.  The code here will
322obviously vary from module to module (dealing with that, after all, is the
323point of find modules), but there tends to be a common pattern for libraries.
324
325First, we try to use ``pkg-config`` to find the library.  Note that we
326cannot rely on this, as it may not be available, but it provides a good
327starting point.
328
329.. code-block:: cmake
330
331  find_package(PkgConfig)
332  pkg_check_modules(PC_Foo QUIET Foo)
333
334This should define some variables starting ``PC_Foo_`` that contain the
335information from the ``Foo.pc`` file.
336
337Now we need to find the libraries and include files; we use the
338information from ``pkg-config`` to provide hints to CMake about where to
339look.
340
341.. code-block:: cmake
342
343  find_path(Foo_INCLUDE_DIR
344    NAMES foo.h
345    PATHS ${PC_Foo_INCLUDE_DIRS}
346    PATH_SUFFIXES Foo
347  )
348  find_library(Foo_LIBRARY
349    NAMES foo
350    PATHS ${PC_Foo_LIBRARY_DIRS}
351  )
352
353Alternatively, if the library is available with multiple configurations, you can
354use :module:`SelectLibraryConfigurations` to automatically set the
355``Foo_LIBRARY`` variable instead:
356
357.. code-block:: cmake
358
359  find_library(Foo_LIBRARY_RELEASE
360    NAMES foo
361    PATHS ${PC_Foo_LIBRARY_DIRS}/Release
362  )
363  find_library(Foo_LIBRARY_DEBUG
364    NAMES foo
365    PATHS ${PC_Foo_LIBRARY_DIRS}/Debug
366  )
367
368  include(SelectLibraryConfigurations)
369  select_library_configurations(Foo)
370
371If you have a good way of getting the version (from a header file, for
372example), you can use that information to set ``Foo_VERSION`` (although
373note that find modules have traditionally used ``Foo_VERSION_STRING``,
374so you may want to set both).  Otherwise, attempt to use the information
375from ``pkg-config``
376
377.. code-block:: cmake
378
379  set(Foo_VERSION ${PC_Foo_VERSION})
380
381Now we can use :module:`FindPackageHandleStandardArgs` to do most of the
382rest of the work for us
383
384.. code-block:: cmake
385
386  include(FindPackageHandleStandardArgs)
387  find_package_handle_standard_args(Foo
388    FOUND_VAR Foo_FOUND
389    REQUIRED_VARS
390      Foo_LIBRARY
391      Foo_INCLUDE_DIR
392    VERSION_VAR Foo_VERSION
393  )
394
395This will check that the ``REQUIRED_VARS`` contain values (that do not
396end in ``-NOTFOUND``) and set ``Foo_FOUND`` appropriately.  It will also
397cache those values.  If ``Foo_VERSION`` is set, and a required version
398was passed to :command:`find_package`, it will check the requested version
399against the one in ``Foo_VERSION``.  It will also print messages as
400appropriate; note that if the package was found, it will print the
401contents of the first required variable to indicate where it was found.
402
403At this point, we have to provide a way for users of the find module to
404link to the library or libraries that were found.  There are two
405approaches, as discussed in the `Find Modules`_ section above.  The
406traditional variable approach looks like
407
408.. code-block:: cmake
409
410  if(Foo_FOUND)
411    set(Foo_LIBRARIES ${Foo_LIBRARY})
412    set(Foo_INCLUDE_DIRS ${Foo_INCLUDE_DIR})
413    set(Foo_DEFINITIONS ${PC_Foo_CFLAGS_OTHER})
414  endif()
415
416If more than one library was found, all of them should be included in
417these variables (see the `Standard Variable Names`_ section for more
418information).
419
420When providing imported targets, these should be namespaced (hence the
421``Foo::`` prefix); CMake will recognize that values passed to
422:command:`target_link_libraries` that contain ``::`` in their name are
423supposed to be imported targets (rather than just library names), and
424will produce appropriate diagnostic messages if that target does not
425exist (see policy :policy:`CMP0028`).
426
427.. code-block:: cmake
428
429  if(Foo_FOUND AND NOT TARGET Foo::Foo)
430    add_library(Foo::Foo UNKNOWN IMPORTED)
431    set_target_properties(Foo::Foo PROPERTIES
432      IMPORTED_LOCATION "${Foo_LIBRARY}"
433      INTERFACE_COMPILE_OPTIONS "${PC_Foo_CFLAGS_OTHER}"
434      INTERFACE_INCLUDE_DIRECTORIES "${Foo_INCLUDE_DIR}"
435    )
436  endif()
437
438One thing to note about this is that the ``INTERFACE_INCLUDE_DIRECTORIES`` and
439similar properties should only contain information about the target itself, and
440not any of its dependencies.  Instead, those dependencies should also be
441targets, and CMake should be told that they are dependencies of this target.
442CMake will then combine all the necessary information automatically.
443
444The type of the :prop_tgt:`IMPORTED` target created in the
445:command:`add_library` command can always be specified as ``UNKNOWN``
446type.  This simplifies the code in cases where static or shared variants may
447be found, and CMake will determine the type by inspecting the files.
448
449If the library is available with multiple configurations, the
450:prop_tgt:`IMPORTED_CONFIGURATIONS` target property should also be
451populated:
452
453.. code-block:: cmake
454
455  if(Foo_FOUND)
456    if (NOT TARGET Foo::Foo)
457      add_library(Foo::Foo UNKNOWN IMPORTED)
458    endif()
459    if (Foo_LIBRARY_RELEASE)
460      set_property(TARGET Foo::Foo APPEND PROPERTY
461        IMPORTED_CONFIGURATIONS RELEASE
462      )
463      set_target_properties(Foo::Foo PROPERTIES
464        IMPORTED_LOCATION_RELEASE "${Foo_LIBRARY_RELEASE}"
465      )
466    endif()
467    if (Foo_LIBRARY_DEBUG)
468      set_property(TARGET Foo::Foo APPEND PROPERTY
469        IMPORTED_CONFIGURATIONS DEBUG
470      )
471      set_target_properties(Foo::Foo PROPERTIES
472        IMPORTED_LOCATION_DEBUG "${Foo_LIBRARY_DEBUG}"
473      )
474    endif()
475    set_target_properties(Foo::Foo PROPERTIES
476      INTERFACE_COMPILE_OPTIONS "${PC_Foo_CFLAGS_OTHER}"
477      INTERFACE_INCLUDE_DIRECTORIES "${Foo_INCLUDE_DIR}"
478    )
479  endif()
480
481The ``RELEASE`` variant should be listed first in the property
482so that the variant is chosen if the user uses a configuration which is
483not an exact match for any listed ``IMPORTED_CONFIGURATIONS``.
484
485Most of the cache variables should be hidden in the ``ccmake`` interface unless
486the user explicitly asks to edit them.
487
488.. code-block:: cmake
489
490  mark_as_advanced(
491    Foo_INCLUDE_DIR
492    Foo_LIBRARY
493  )
494
495If this module replaces an older version, you should set compatibility variables
496to cause the least disruption possible.
497
498.. code-block:: cmake
499
500  # compatibility variables
501  set(Foo_VERSION_STRING ${Foo_VERSION})
502