cmake-developer.7.rst 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. .. cmake-manual-description: CMake Developer Reference
  2. cmake-developer(7)
  3. ******************
  4. .. only:: html or latex
  5. .. contents::
  6. Introduction
  7. ============
  8. This manual is intended for reference by developers modifying the CMake
  9. source tree itself.
  10. Permitted C++ Subset
  11. ====================
  12. CMake is required to build with ancient C++ compilers and standard library
  13. implementations. Some common C++ constructs may not be used in CMake in order
  14. to build with such toolchains.
  15. std::vector::at
  16. ---------------
  17. The ``at()`` member function of ``std::vector`` may not be used. Use
  18. ``operator[]`` instead:
  19. .. code-block:: c++
  20. std::vector<int> someVec = getVec();
  21. int i1 = someVec.at(5); // Wrong
  22. int i2 = someVec[5]; // Ok
  23. std::string::append and std::string::clear
  24. ------------------------------------------
  25. The ``append()`` and ``clear()`` member functions of ``std::string`` may not
  26. be used. Use ``operator+=`` and ``operator=`` instead:
  27. .. code-block:: c++
  28. std::string stringBuilder;
  29. stringBuilder.append("chunk"); // Wrong
  30. stringBuilder.clear(); // Wrong
  31. stringBuilder += "chunk"; // Ok
  32. stringBuilder = ""; // Ok
  33. std::set const iterators
  34. ------------------------
  35. The ``find()`` member function of a ``const`` ``std::set`` instance may not be
  36. used in a comparison with the iterator returned by ``end()``:
  37. .. code-block:: c++
  38. const std::set<std::string>& someSet = getSet();
  39. if (someSet.find("needle") == someSet.end()) // Wrong
  40. {
  41. // ...
  42. }
  43. The return value of ``find()`` must be assigned to an intermediate
  44. ``const_iterator`` for comparison:
  45. .. code-block:: c++
  46. const std::set<std::string>& someSet;
  47. const std::set<std::string>::const_iterator i = someSet.find("needle");
  48. if (i != propSet.end()) // Ok
  49. {
  50. // ...
  51. }
  52. Char Array to ``string`` Conversions with Algorithms
  53. ----------------------------------------------------
  54. In some implementations, algorithms operating on iterators to a container of
  55. ``std::string`` can not accept a ``const char*`` value:
  56. .. code-block:: c++
  57. const char* dir = /*...*/;
  58. std::vector<std::string> vec;
  59. // ...
  60. std::binary_search(vec.begin(), vec.end(), dir); // Wrong
  61. The ``std::string`` may need to be explicitly constructed:
  62. .. code-block:: c++
  63. const char* dir = /*...*/;
  64. std::vector<std::string> vec;
  65. // ...
  66. std::binary_search(vec.begin(), vec.end(), std::string(dir)); // Ok
  67. std::auto_ptr
  68. -------------
  69. Some implementations have a ``std::auto_ptr`` which can not be used as a
  70. return value from a function. ``std::auto_ptr`` may not be used. Use
  71. ``cmsys::auto_ptr`` instead.
  72. std::vector::insert and std::set
  73. --------------------------------
  74. Use of ``std::vector::insert`` with an iterator whose ``element_type`` requires
  75. conversion is not allowed:
  76. .. code-block:: c++
  77. std::set<const char*> theSet;
  78. std::vector<std::string> theVector;
  79. theVector.insert(theVector.end(), theSet.begin(), theSet.end()); // Wrong
  80. A loop must be used instead:
  81. .. code-block:: c++
  82. std::set<const char*> theSet;
  83. std::vector<std::string> theVector;
  84. for(std::set<const char*>::iterator li = theSet.begin();
  85. li != theSet.end(); ++li)
  86. {
  87. theVector.push_back(*li);
  88. }
  89. std::set::insert
  90. ----------------
  91. Use of ``std::set::insert`` is not allowed with any source container:
  92. .. code-block:: c++
  93. std::set<cmTarget*> theSet;
  94. theSet.insert(targets.begin(), targets.end()); // Wrong
  95. A loop must be used instead:
  96. .. code-block:: c++
  97. ConstIterator it = targets.begin();
  98. const ConstIterator end = targets.end();
  99. for ( ; it != end; ++it)
  100. {
  101. theSet.insert(*it);
  102. }
  103. .. MSVC6, SunCC 5.9
  104. Template Parameter Defaults
  105. ---------------------------
  106. On ancient compilers, C++ template must use template parameters in function
  107. arguments. If no parameter of that type is needed, the common workaround is
  108. to add a defaulted pointer to the type to the templated function. However,
  109. this does not work with other ancient compilers:
  110. .. code-block:: c++
  111. template<typename PropertyType>
  112. PropertyType getTypedProperty(cmTarget* tgt, const char* prop,
  113. PropertyType* = 0) // Wrong
  114. {
  115. }
  116. .. code-block:: c++
  117. template<typename PropertyType>
  118. PropertyType getTypedProperty(cmTarget* tgt, const char* prop,
  119. PropertyType*) // Ok
  120. {
  121. }
  122. and invoke it with the value ``0`` explicitly in all cases.
  123. std::min and std::max
  124. ---------------------
  125. ``min`` and ``max`` are defined as macros on some systems. ``std::min`` and
  126. ``std::max`` may not be used. Use ``cmMinimum`` and ``cmMaximum`` instead.
  127. size_t
  128. ------
  129. Various implementations have differing implementation of ``size_t``. When
  130. assigning the result of ``.size()`` on a container for example, the result
  131. should not be assigned to an ``unsigned int`` or similar. ``std::size_t`` must
  132. not be used.
  133. Templates
  134. ---------
  135. Some template code is permitted, but with some limitations. Member templates
  136. may not be used, and template friends may not be used.
  137. Help
  138. ====
  139. The ``Help`` directory contains CMake help manual source files.
  140. They are written using the `reStructuredText`_ markup syntax and
  141. processed by `Sphinx`_ to generate the CMake help manuals.
  142. .. _`reStructuredText`: http://docutils.sourceforge.net/docs/ref/rst/introduction.html
  143. .. _`Sphinx`: http://sphinx-doc.org
  144. Markup Constructs
  145. -----------------
  146. In addition to using Sphinx to generate the CMake help manuals, we
  147. also use a C++-implemented document processor to print documents for
  148. the ``--help-*`` command-line help options. It supports a subset of
  149. reStructuredText markup. When authoring or modifying documents,
  150. please verify that the command-line help looks good in addition to the
  151. Sphinx-generated html and man pages.
  152. The command-line help processor supports the following constructs
  153. defined by reStructuredText, Sphinx, and a CMake extension to Sphinx.
  154. ..
  155. Note: This list must be kept consistent with the cmRST implementation.
  156. CMake Domain directives
  157. Directives defined in the `CMake Domain`_ for defining CMake
  158. documentation objects are printed in command-line help output as
  159. if the lines were normal paragraph text with interpretation.
  160. CMake Domain interpreted text roles
  161. Interpreted text roles defined in the `CMake Domain`_ for
  162. cross-referencing CMake documentation objects are replaced by their
  163. link text in command-line help output. Other roles are printed
  164. literally and not processed.
  165. ``code-block`` directive
  166. Add a literal code block without interpretation. The command-line
  167. help processor prints the block content without the leading directive
  168. line and with common indentation replaced by one space.
  169. ``include`` directive
  170. Include another document source file. The command-line help
  171. processor prints the included document inline with the referencing
  172. document.
  173. literal block after ``::``
  174. A paragraph ending in ``::`` followed by a blank line treats
  175. the following indented block as literal text without interpretation.
  176. The command-line help processor prints the ``::`` literally and
  177. prints the block content with common indentation replaced by one
  178. space.
  179. ``note`` directive
  180. Call out a side note. The command-line help processor prints the
  181. block content as if the lines were normal paragraph text with
  182. interpretation.
  183. ``parsed-literal`` directive
  184. Add a literal block with markup interpretation. The command-line
  185. help processor prints the block content without the leading
  186. directive line and with common indentation replaced by one space.
  187. ``productionlist`` directive
  188. Render context-free grammar productions. The command-line help
  189. processor prints the block content as if the lines were normal
  190. paragraph text with interpretation.
  191. ``replace`` directive
  192. Define a ``|substitution|`` replacement.
  193. The command-line help processor requires a substitution replacement
  194. to be defined before it is referenced.
  195. ``|substitution|`` reference
  196. Reference a substitution replacement previously defined by
  197. the ``replace`` directive. The command-line help processor
  198. performs the substitution and replaces all newlines in the
  199. replacement text with spaces.
  200. ``toctree`` directive
  201. Include other document sources in the Table-of-Contents
  202. document tree. The command-line help processor prints
  203. the referenced documents inline as part of the referencing
  204. document.
  205. Inline markup constructs not listed above are printed literally in the
  206. command-line help output. We prefer to use inline markup constructs that
  207. look correct in source form, so avoid use of \\-escapes in favor of inline
  208. literals when possible.
  209. Explicit markup blocks not matching directives listed above are removed from
  210. command-line help output. Do not use them, except for plain ``..`` comments
  211. that are removed by Sphinx too.
  212. Note that nested indentation of blocks is not recognized by the
  213. command-line help processor. Therefore:
  214. * Explicit markup blocks are recognized only when not indented
  215. inside other blocks.
  216. * Literal blocks after paragraphs ending in ``::`` but not
  217. at the top indentation level may consume all indented lines
  218. following them.
  219. Try to avoid these cases in practice.
  220. CMake Domain
  221. ------------
  222. CMake adds a `Sphinx Domain`_ called ``cmake``, also called the
  223. "CMake Domain". It defines several "object" types for CMake
  224. documentation:
  225. ``command``
  226. A CMake language command.
  227. ``generator``
  228. A CMake native build system generator.
  229. See the :manual:`cmake(1)` command-line tool's ``-G`` option.
  230. ``manual``
  231. A CMake manual page, like this :manual:`cmake-developer(7)` manual.
  232. ``module``
  233. A CMake module.
  234. See the :manual:`cmake-modules(7)` manual
  235. and the :command:`include` command.
  236. ``policy``
  237. A CMake policy.
  238. See the :manual:`cmake-policies(7)` manual
  239. and the :command:`cmake_policy` command.
  240. ``prop_cache, prop_dir, prop_gbl, prop_sf, prop_test, prop_tgt``
  241. A CMake cache, directory, global, source file, test, or target
  242. property, respectively. See the :manual:`cmake-properties(7)` manual
  243. and the :command:`set_property` command.
  244. ``variable``
  245. A CMake language variable.
  246. See the :manual:`cmake-variables(7)` manual
  247. and the :command:`set` command.
  248. Documentation objects in the CMake Domain come from two sources.
  249. First, the CMake extension to Sphinx transforms every document named
  250. with the form ``Help/<type>/<file-name>.rst`` to a domain object with
  251. type ``<type>``. The object name is extracted from the document title,
  252. which is expected to be of the form::
  253. <object-name>
  254. -------------
  255. and to appear at or near the top of the ``.rst`` file before any other
  256. lines starting in a letter, digit, or ``<``. If no such title appears
  257. literally in the ``.rst`` file, the object name is the ``<file-name>``.
  258. If a title does appear, it is expected that ``<file-name>`` is equal
  259. to ``<object-name>`` with any ``<`` and ``>`` characters removed.
  260. Second, the CMake Domain provides directives to define objects inside
  261. other documents:
  262. .. code-block:: rst
  263. .. command:: <command-name>
  264. This indented block documents <command-name>.
  265. .. variable:: <variable-name>
  266. This indented block documents <variable-name>.
  267. Object types for which no directive is available must be defined using
  268. the first approach above.
  269. .. _`Sphinx Domain`: http://sphinx-doc.org/domains.html
  270. Cross-References
  271. ----------------
  272. Sphinx uses reStructuredText interpreted text roles to provide
  273. cross-reference syntax. The `CMake Domain`_ provides for each
  274. domain object type a role of the same name to cross-reference it.
  275. CMake Domain roles are inline markup of the forms::
  276. :type:`name`
  277. :type:`text <name>`
  278. where ``type`` is the domain object type and ``name`` is the
  279. domain object name. In the first form the link text will be
  280. ``name`` (or ``name()`` if the type is ``command``) and in
  281. the second form the link text will be the explicit ``text``.
  282. For example, the code:
  283. .. code-block:: rst
  284. * The :command:`list` command.
  285. * The :command:`list(APPEND)` sub-command.
  286. * The :command:`list() command <list>`.
  287. * The :command:`list(APPEND) sub-command <list>`.
  288. * The :variable:`CMAKE_VERSION` variable.
  289. * The :prop_tgt:`OUTPUT_NAME_<CONFIG>` target property.
  290. produces:
  291. * The :command:`list` command.
  292. * The :command:`list(APPEND)` sub-command.
  293. * The :command:`list() command <list>`.
  294. * The :command:`list(APPEND) sub-command <list>`.
  295. * The :variable:`CMAKE_VERSION` variable.
  296. * The :prop_tgt:`OUTPUT_NAME_<CONFIG>` target property.
  297. Note that CMake Domain roles differ from Sphinx and reStructuredText
  298. convention in that the form ``a<b>``, without a space preceding ``<``,
  299. is interpreted as a name instead of link text with an explicit target.
  300. This is necessary because we use ``<placeholders>`` frequently in
  301. object names like ``OUTPUT_NAME_<CONFIG>``. The form ``a <b>``,
  302. with a space preceding ``<``, is still interpreted as a link text
  303. with an explicit target.
  304. Style
  305. -----
  306. 1)
  307. Command signatures should be marked up as plain literal blocks, not as
  308. cmake ``code-blocks``.
  309. 2)
  310. Signatures are separated from preceding content by a horizontal
  311. line. That is, use:
  312. .. code-block:: rst
  313. ... preceding paragraph.
  314. ---------------------------------------------------------------------
  315. ::
  316. add_library(<lib> ...)
  317. This signature is used for ...
  318. 3)
  319. Use "``OFF``" and "``ON``" for boolean values which can be modified by
  320. the user, such as :prop_tgt:`POSITION_INDEPENDENT_CODE`. Such properties
  321. may be "enabled" and "disabled". Use "``True``" and "``False``" for
  322. inherent values which can't be modified after being set, such as the
  323. :prop_tgt:`IMPORTED` property of a build target.
  324. 4)
  325. Use two spaces for indentation. Use two spaces between sentences in
  326. prose.
  327. 5)
  328. Prefer to mark the start of literal blocks with ``::`` at the end of
  329. the preceding paragraph. In cases where the following block gets
  330. a ``code-block`` marker, put a single ``:`` at the end of the preceding
  331. paragraph.
  332. 6)
  333. Prefer to restrict the width of lines to 75-80 columns. This is not a
  334. hard restriction, but writing new paragraphs wrapped at 75 columns
  335. allows space for adding minor content without significant re-wrapping of
  336. content.
  337. 7)
  338. Mark up self-references with ``inline-literal`` syntax. For example,
  339. within the add_executable command documentation, use
  340. .. code-block:: rst
  341. ``add_executable``
  342. not
  343. .. code-block:: rst
  344. :command:`add_executable`
  345. which is used elsewhere.
  346. 8)
  347. Mark up all other linkable references as links, including repeats. An
  348. alternative, which is used by wikipedia (`<http://en.wikipedia.org/wiki/WP:REPEATLINK>`_),
  349. is to link to a reference only once per article. That style is not used
  350. in CMake documentation.
  351. 9)
  352. Mark up references to keywords in signatures, file names, and other
  353. technical terms with ``inline-literl`` syntax, for example:
  354. .. code-block:: rst
  355. If ``WIN32`` is used with :command:`add_executable`, the
  356. :prop_tgt:`WIN32_EXECUTABLE` target property is enabled. That command
  357. creates the file ``<name>.exe`` on Windows.
  358. 10)
  359. If referring to a concept which corresponds to a property, and that
  360. concept is described in a high-level manual, prefer to link to the
  361. manual section instead of the property. For example:
  362. .. code-block:: rst
  363. This command creates an :ref:`Imported Target <Imported Targets>`.
  364. instead of:
  365. .. code-block:: rst
  366. This command creates an :prop_tgt:`IMPORTED` target.
  367. The latter should be used only when referring specifically to the
  368. property.
  369. References to manual sections are not automatically created by creating
  370. a section, but code such as:
  371. .. code-block:: rst
  372. .. _`Imported Targets`:
  373. creates a suitable anchor. Use an anchor name which matches the name
  374. of the corresponding section. Refer to the anchor using a
  375. cross-reference with specified text.
  376. Imported Targets need the ``IMPORTED`` term marked up with care in
  377. particular because the term may refer to a command keyword
  378. (``IMPORTED``), a target property (:prop_tgt:`IMPORTED`), or a
  379. concept (:ref:`Imported Targets`).
  380. 11)
  381. Where a property, command or variable is related conceptually to others,
  382. by for example, being related to the buildsystem description, generator
  383. expressions or Qt, each relevant property, command or variable should
  384. link to the primary manual, which provides high-level information. Only
  385. particular information relating to the command should be in the
  386. documentation of the command.
  387. 12)
  388. When marking section titles, make the section decoration line as long as
  389. the title text. Use only a line below the title, not above. For
  390. example:
  391. .. code-block:: rst
  392. Title Text
  393. ----------
  394. Capitalize the first letter of each non-minor word in the title.
  395. 13)
  396. When referring to properties, variables, commands etc, prefer to link
  397. to the target object and follow that with the type of object it is.
  398. For example:
  399. .. code-block:: rst
  400. Set the :prop_tgt:`AUTOMOC` target property to ``ON``.
  401. Instead of
  402. .. code-block:: rst
  403. Set the target property :prop_tgt:`AUTOMOC` to ``ON``.
  404. The ``policy`` directive is an exception, and the type us usually
  405. referred to before the link:
  406. .. code-block:: rst
  407. If policy :prop_tgt:`CMP0022` is set to ``NEW`` the behavior is ...
  408. 14)
  409. Signatures of commands should wrap optional parts with square brackets,
  410. and should mark list of optional arguments with an ellipsis (``...``).
  411. Elements of the signature which are specified by the user should be
  412. specified with angle brackets, and may be referred to in prose using
  413. ``inline-literal`` syntax.
  414. 15)
  415. Use American English spellings in prose.
  416. Modules
  417. =======
  418. The ``Modules`` directory contains CMake-language ``.cmake`` module files.
  419. Module Documentation
  420. --------------------
  421. To document CMake module ``Modules/<module-name>.cmake``, modify
  422. ``Help/manual/cmake-modules.7.rst`` to reference the module in the
  423. ``toctree`` directive, in sorted order, as::
  424. /module/<module-name>
  425. Then add the module document file ``Help/module/<module-name>.rst``
  426. containing just the line::
  427. .. cmake-module:: ../../Modules/<module-name>.cmake
  428. The ``cmake-module`` directive will scan the module file to extract
  429. reStructuredText markup from comment blocks that start in ``.rst:``.
  430. Add to the top of ``Modules/<module-name>.cmake`` a
  431. :ref:`Line Comment` block of the form:
  432. .. code-block:: cmake
  433. #.rst:
  434. # <module-name>
  435. # -------------
  436. #
  437. # <reStructuredText documentation of module>
  438. or a :ref:`Bracket Comment` of the form:
  439. .. code-block:: cmake
  440. #[[.rst:
  441. <module-name>
  442. -------------
  443. <reStructuredText documentation of module>
  444. #]]
  445. Any number of ``=`` may be used in the opening and closing brackets
  446. as long as they match. Content on the line containing the closing
  447. bracket is excluded if and only if the line starts in ``#``.
  448. Additional such ``.rst:`` comments may appear anywhere in the module file.
  449. All such comments must start with ``#`` in the first column.
  450. For example, a ``Modules/Findxxx.cmake`` module may contain:
  451. .. code-block:: cmake
  452. #.rst:
  453. # FindXxx
  454. # -------
  455. #
  456. # This is a cool module.
  457. # This module does really cool stuff.
  458. # It can do even more than you think.
  459. #
  460. # It even needs two paragraphs to tell you about it.
  461. # And it defines the following variables:
  462. #
  463. # * VAR_COOL: this is great isn't it?
  464. # * VAR_REALLY_COOL: cool right?
  465. <code>
  466. #[========================================[.rst:
  467. .. command:: xxx_do_something
  468. This command does something for Xxx::
  469. xxx_do_something(some arguments)
  470. #]========================================]
  471. macro(xxx_do_something)
  472. <code>
  473. endmacro()
  474. After the top documentation block, leave a *BLANK* line, and then add a
  475. copyright and licence notice block like this one (change only the year
  476. range and name)
  477. .. code-block:: cmake
  478. #=============================================================================
  479. # Copyright 2009-2011 Your Name
  480. #
  481. # Distributed under the OSI-approved BSD License (the "License");
  482. # see accompanying file Copyright.txt for details.
  483. #
  484. # This software is distributed WITHOUT ANY WARRANTY; without even the
  485. # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  486. # See the License for more information.
  487. #=============================================================================
  488. # (To distribute this file outside of CMake, substitute the full
  489. # License text for the above reference.)
  490. Test the documentation formatting by running
  491. ``cmake --help-module <module-name>``, and also by enabling the
  492. ``SPHINX_HTML`` and ``SPHINX_MAN`` options to build the documentation.
  493. Edit the comments until generated documentation looks satisfactory. To
  494. have a .cmake file in this directory NOT show up in the modules
  495. documentation, simply leave out the ``Help/module/<module-name>.rst``
  496. file and the ``Help/manual/cmake-modules.7.rst`` toctree entry.
  497. Find Modules
  498. ------------
  499. A "find module" is a ``Modules/Find<package>.cmake`` file to be loaded
  500. by the :command:`find_package` command when invoked for ``<package>``.
  501. The primary task of a find module is to determine whether a package
  502. exists on the system, set the ``<package>_FOUND`` variable to reflect
  503. this and provide any variables, macros and imported targets required to
  504. use the package.
  505. The traditional approach is to use variables for everything, including
  506. libraries and executables: see the `Standard Variable Names`_ section
  507. below. This is what most of the existing find modules provided by CMake
  508. do.
  509. The more modern approach is to behave as much like
  510. ``<package>Config.cmake`` files as possible, by providing imported
  511. targets. As well as matching how ``*Config.cmake`` files work, the
  512. libraries, include directories and compile definitions are all set just
  513. by using the target in a :command:`target_link_libraries` call. The
  514. disadvantage is that ``*Config.cmake`` files of projects that use
  515. imported targets from find modules may require more work to make sure
  516. those imported targets that are in the link interface are available.
  517. In either case (or even when providing both variables and imported
  518. targets), find modules should provide backwards compatibility with old
  519. versions that had the same name.
  520. A FindFoo.cmake module will typically be loaded by the command::
  521. find_package(Foo [major[.minor[.patch[.tweak]]]]
  522. [EXACT] [QUIET] [REQUIRED]
  523. [[COMPONENTS] [components...]]
  524. [OPTIONAL_COMPONENTS components...]
  525. [NO_POLICY_SCOPE])
  526. See the :command:`find_package` documentation for details on what
  527. variables are set for the find module. Most of these are dealt with by
  528. using :module:`FindPackageHandleStandardArgs`.
  529. Briefly, the module should only locate versions of the package
  530. compatible with the requested version, as described by the
  531. ``Foo_FIND_VERSION`` family of variables. If ``Foo_FIND_QUIETLY`` is
  532. set to true, it should avoid printing messages, including anything
  533. complaining about the package not being found. If ``Foo_FIND_REQUIRED``
  534. is set to true, the module should issue a ``FATAL_ERROR`` if the package
  535. cannot be found. If neither are set to true, it should print a
  536. non-fatal message if it cannot find the package.
  537. Packages that find multiple semi-independent parts (like bundles of
  538. libraries) should search for the components listed in
  539. ``Foo_FIND_COMPONENTS`` if it is set , and only set ``Foo_FOUND`` to
  540. true if for each searched-for component ``<c>`` that was not found,
  541. ``Foo_FIND_REQUIRED_<c>`` is not set to true. The ``HANDLE_COMPONENTS``
  542. argument of ``find_package_handle_standard_args()`` can be used to
  543. implement this.
  544. If ``Foo_FIND_COMPONENTS`` is not set, which modules are searched for
  545. and required is up to the find module, but should be documented.
  546. For internal implementation, it is a generally accepted convention that
  547. variables starting with underscore are for temporary use only.
  548. Like all modules, find modules should be properly documented. To add a
  549. module to the CMake documentation, follow the steps in the `Module
  550. Documentation`_ section above.
  551. Standard Variable Names
  552. ~~~~~~~~~~~~~~~~~~~~~~~
  553. For a ``FindXxx.cmake`` module that takes the approach of setting
  554. variables (either instead of or in addition to creating imported
  555. targets), the following variable names should be used to keep things
  556. consistent between find modules. Note that all variables start with
  557. ``Xxx_`` to make sure they do not interfere with other find modules; the
  558. same consideration applies to macros, functions and imported targets.
  559. ``Xxx_INCLUDE_DIRS``
  560. The final set of include directories listed in one variable for use by
  561. client code. This should not be a cache entry.
  562. ``Xxx_LIBRARIES``
  563. The libraries to link against to use Xxx. These should include full
  564. paths. This should not be a cache entry.
  565. ``Xxx_DEFINITIONS``
  566. Definitions to use when compiling code that uses Xxx. This really
  567. shouldn't include options such as ``-DHAS_JPEG`` that a client
  568. source-code file uses to decide whether to ``#include <jpeg.h>``
  569. ``Xxx_EXECUTABLE``
  570. Where to find the Xxx tool.
  571. ``Xxx_Yyy_EXECUTABLE``
  572. Where to find the Yyy tool that comes with Xxx.
  573. ``Xxx_LIBRARY_DIRS``
  574. Optionally, the final set of library directories listed in one
  575. variable for use by client code. This should not be a cache entry.
  576. ``Xxx_ROOT_DIR``
  577. Where to find the base directory of Xxx.
  578. ``Xxx_VERSION_Yy``
  579. Expect Version Yy if true. Make sure at most one of these is ever true.
  580. ``Xxx_WRAP_Yy``
  581. If False, do not try to use the relevant CMake wrapping command.
  582. ``Xxx_Yy_FOUND``
  583. If False, optional Yy part of Xxx sytem is not available.
  584. ``Xxx_FOUND``
  585. Set to false, or undefined, if we haven't found, or don't want to use
  586. Xxx.
  587. ``Xxx_NOT_FOUND_MESSAGE``
  588. Should be set by config-files in the case that it has set
  589. ``Xxx_FOUND`` to FALSE. The contained message will be printed by the
  590. :command:`find_package` command and by
  591. ``find_package_handle_standard_args()`` to inform the user about the
  592. problem.
  593. ``Xxx_RUNTIME_LIBRARY_DIRS``
  594. Optionally, the runtime library search path for use when running an
  595. executable linked to shared libraries. The list should be used by
  596. user code to create the ``PATH`` on windows or ``LD_LIBRARY_PATH`` on
  597. UNIX. This should not be a cache entry.
  598. ``Xxx_VERSION``
  599. The full version string of the package found, if any. Note that many
  600. existing modules provide ``Xxx_VERSION_STRING`` instead.
  601. ``Xxx_VERSION_MAJOR``
  602. The major version of the package found, if any.
  603. ``Xxx_VERSION_MINOR``
  604. The minor version of the package found, if any.
  605. ``Xxx_VERSION_PATCH``
  606. The patch version of the package found, if any.
  607. The following names should not usually be used in CMakeLists.txt files, but
  608. are typically cache variables for users to edit and control the
  609. behaviour of find modules (like entering the path to a library manually)
  610. ``Xxx_LIBRARY``
  611. The path of the Xxx library (as used with :command:`find_library`, for
  612. example).
  613. ``Xxx_Yy_LIBRARY``
  614. The path of the Yy library that is part of the Xxx system. It may or
  615. may not be required to use Xxx.
  616. ``Xxx_INCLUDE_DIR``
  617. Where to find headers for using the Xxx library.
  618. ``Xxx_Yy_INCLUDE_DIR``
  619. Where to find headers for using the Yy library of the Xxx system.
  620. To prevent users being overwhelmed with settings to configure, try to
  621. keep as many options as possible out of the cache, leaving at least one
  622. option which can be used to disable use of the module, or locate a
  623. not-found library (e.g. ``Xxx_ROOT_DIR``). For the same reason, mark
  624. most cache options as advanced.
  625. While these are the standard variable names, you should provide
  626. backwards compatibility for any old names that were actually in use.
  627. Make sure you comment them as deprecated, so that no-one starts using
  628. them.
  629. A Sample Find Module
  630. ~~~~~~~~~~~~~~~~~~~~
  631. We will describe how to create a simple find module for a library
  632. ``Foo``.
  633. The first thing that is needed is documentation. CMake's documentation
  634. system requires you to start the file with a documentation marker and
  635. the name of the module. You should follow this with a simple statement
  636. of what the module does.
  637. .. code-block:: cmake
  638. #.rst:
  639. # FindFoo
  640. # -------
  641. #
  642. # Finds the Foo library
  643. #
  644. More description may be required for some packages. If there are
  645. caveats or other details users of the module should be aware of, you can
  646. add further paragraphs below this. Then you need to document what
  647. variables and imported targets are set by the module, such as
  648. .. code-block:: cmake
  649. # This will define the following variables::
  650. #
  651. # Foo_FOUND - True if the system has the Foo library
  652. # Foo_VERSION - The version of the Foo library which was found
  653. #
  654. # and the following imported targets::
  655. #
  656. # Foo::Foo - The Foo library
  657. If the package provides any macros, they should be listed here, but can
  658. be documented where they are defined. See the `Module
  659. Documentation`_ section above for more details.
  660. After the documentation, leave a blank line, and then add a copyright and
  661. licence notice block
  662. .. code-block:: cmake
  663. #=============================================================================
  664. # Copyright 2009-2011 Your Name
  665. #
  666. # Distributed under the OSI-approved BSD License (the "License");
  667. # see accompanying file Copyright.txt for details.
  668. #
  669. # This software is distributed WITHOUT ANY WARRANTY; without even the
  670. # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  671. # See the License for more information.
  672. #=============================================================================
  673. # (To distribute this file outside of CMake, substitute the full
  674. # License text for the above reference.)
  675. If the module is new to CMake, you may want to provide a warning for
  676. projects that do not require a high enough CMake version.
  677. .. code-block:: cmake
  678. if(CMAKE_MINIMUM_REQUIRED_VERSION VERSION_LESS 3.0.0)
  679. message(AUTHOR_WARNING "Your project should require at least CMake 3.0.0 to use FindFoo.cmake")
  680. endif()
  681. Now the actual libraries and so on have to be found. The code here will
  682. obviously vary from module to module (dealing with that, after all, is the
  683. point of find modules), but there tends to be a common pattern for libraries.
  684. First, we try to use ``pkg-config`` to find the library. Note that we
  685. cannot rely on this, as it may not be available, but it provides a good
  686. starting point.
  687. .. code-block:: cmake
  688. find_package(PkgConfig)
  689. pkg_check_modules(PC_Foo QUIET Foo)
  690. This should define some variables starting ``PC_Foo_`` that contain the
  691. information from the ``Foo.pc`` file.
  692. Now we need to find the libraries and include files; we use the
  693. information from ``pkg-config`` to provide hints to CMake about where to
  694. look.
  695. .. code-block:: cmake
  696. find_path(Foo_INCLUDE_DIR
  697. NAMES foo.h
  698. PATHS ${PC_Foo_INCLUDE_DIRS}
  699. # if you need to put #include <Foo/foo.h> in your code, add:
  700. PATH_SUFFIXES Foo
  701. )
  702. find_library(Foo_LIBRARY
  703. NAMES foo
  704. PATHS ${PC_Foo_LIBRARY_DIRS}
  705. )
  706. If you have a good way of getting the version (from a header file, for
  707. example), you can use that information to set ``Foo_VERSION`` (although
  708. note that find modules have traditionally used ``Foo_VERSION_STRING``,
  709. so you may want to set both). Otherwise, attempt to use the information
  710. from ``pkg-config``
  711. .. code-block:: cmake
  712. set(Foo_VERSION ${PC_Foo_VERSION})
  713. Now we can use :module:`FindPackageHandleStandardArgs` to do most of the
  714. rest of the work for us
  715. .. code-block:: cmake
  716. include(FindPackageHandleStandardArgs)
  717. find_package_handle_standard_args(Foo
  718. FOUND_VAR Foo_FOUND
  719. REQUIRED_VARS
  720. Foo_LIBRARY
  721. Foo_INCLUDE_DIR
  722. VERSION_VAR Foo_VERSION
  723. )
  724. This will check that the ``REQUIRED_VARS`` contain values (that do not
  725. end in ``-NOTFOUND``) and set ``Foo_FOUND`` appropriately. It will also
  726. cache those values. If ``Foo_VERSION`` is set, and a required version
  727. was passed to :command:`find_package`, it will check the requested version
  728. against the one in ``Foo_VERSION``. It will also print messages as
  729. appropriate; note that if the package was found, it will print the
  730. contents of the first required variable to indicate where it was found.
  731. At this point, we have to provide a way for users of the find module to
  732. link to the library or libraries that were found. There are two
  733. approaches, as discussed in the `Find Modules`_ section above. The
  734. traditional variable approach looks like
  735. .. code-block:: cmake
  736. if(Foo_FOUND)
  737. set(Foo_LIBRARIES ${Foo_LIBRARY})
  738. set(Foo_INCLUDE_DIRS ${Foo_INCLUDE_DIR})
  739. set(Foo_DEFINITIONS ${PC_Foo_CFLAGS_OTHER})
  740. endif()
  741. If more than one library was found, all of them should be included in
  742. these variables (see the `Standard Variable Names`_ section for more
  743. information).
  744. When providing imported targets, these should be namespaced (hence the
  745. ``Foo::`` prefix); CMake will recognize that values passed to
  746. :command:`target_link_libraries` that contain ``::`` in their name are
  747. supposed to be imported targets (rather than just library names), and
  748. will produce appropriate diagnostic messages if that target does not
  749. exist (see policy :policy:`CMP0028`).
  750. .. code-block:: cmake
  751. if(Foo_FOUND AND NOT TARGET Foo::Foo)
  752. add_library(Foo::Foo UNKNOWN IMPORTED)
  753. set_target_properties(Foo::Foo PROPERTIES
  754. IMPORTED_LOCATION "${Foo_LIBRARY}"
  755. INTERFACE_COMPILE_OPTIONS "${PC_Foo_CFLAGS_OTHER}"
  756. INTERFACE_INCLUDE_DIRECTORIES "${Foo_INCLUDE_DIR}"
  757. )
  758. endif()
  759. One thing to note about this is that the ``INTERFACE_INCLUDE_DIRECTORIES`` and
  760. similar properties should only contain information about the target itself, and
  761. not any of its dependencies. Instead, those dependencies should also be
  762. targets, and CMake should be told that they are dependencies of this target.
  763. CMake will then combine all the necessary information automatically.
  764. We should also provide some information about the package, such as where to
  765. download it.
  766. .. code-block:: cmake
  767. include(FeatureSummary)
  768. set_package_properties(Foo PROPERTIES
  769. URL "http://www.foo.example.com/"
  770. DESCRIPTION "A library for doing useful things"
  771. )
  772. Most of the cache variables should be hidden in the ``ccmake`` interface unless
  773. the user explicitly asks to edit them.
  774. .. code-block:: cmake
  775. mark_as_advanced(
  776. Foo_INCLUDE_DIR
  777. Foo_LIBRARY
  778. )
  779. If this module replaces an older version, you should set compatibility variables
  780. to cause the least disruption possible.
  781. .. code-block:: cmake
  782. # compatibility variables
  783. set(Foo_VERSION_STRING ${Foo_VERSION})