1
0

cmake-developer.7.rst 37 KB

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