index.rst 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. CMake Tutorial
  2. **************
  3. .. only:: html
  4. .. contents::
  5. The CMake tutorial provides a step-by-step guide that covers common build
  6. system issues that CMake helps address. Seeing how various topics all
  7. work together in an example project can be very helpful. The tutorial
  8. documentation and source code for examples can be found in the
  9. ``Help/guide/tutorial`` directory of the CMake source code tree. Each step has
  10. its own subdirectory containing code that may be used as a starting point. The
  11. tutorial examples are progressive so that each step provides the complete
  12. solution for the previous step.
  13. A Basic Starting Point (Step 1)
  14. ===============================
  15. The most basic project is an executable built from source code files.
  16. For simple projects, a three line ``CMakeLists.txt`` file is all that is
  17. required. This will be the starting point for our tutorial. Create a
  18. ``CMakeLists.txt`` file in the ``Step1`` directory that looks like:
  19. .. code-block:: cmake
  20. cmake_minimum_required(VERSION 3.10)
  21. # set the project name
  22. project(Tutorial)
  23. # add the executable
  24. add_executable(Tutorial tutorial.cxx)
  25. Note that this example uses lower case commands in the ``CMakeLists.txt`` file.
  26. Upper, lower, and mixed case commands are supported by CMake. The source
  27. code for ``tutorial.cxx`` is provided in the ``Step1`` directory and can be
  28. used to compute the square root of a number.
  29. Adding a Version Number and Configured Header File
  30. --------------------------------------------------
  31. The first feature we will add is to provide our executable and project with a
  32. version number. While we could do this exclusively in the source code, using
  33. ``CMakeLists.txt`` provides more flexibility.
  34. First, modify the ``CMakeLists.txt`` file to use the :command:`project` command
  35. to set the project name and version number.
  36. .. literalinclude:: Step2/CMakeLists.txt
  37. :language: cmake
  38. :end-before: # specify the C++ standard
  39. Then, configure a header file to pass the version number to the source
  40. code:
  41. .. literalinclude:: Step2/CMakeLists.txt
  42. :language: cmake
  43. :start-after: # to the source code
  44. :end-before: # add the executable
  45. Since the configured file will be written into the binary tree, we
  46. must add that directory to the list of paths to search for include
  47. files. Add the following lines to the end of the ``CMakeLists.txt`` file:
  48. .. literalinclude:: Step2/CMakeLists.txt
  49. :language: cmake
  50. :start-after: # so that we will find TutorialConfig.h
  51. Using your favorite editor, create ``TutorialConfig.h.in`` in the source
  52. directory with the following contents:
  53. .. literalinclude:: Step2/TutorialConfig.h.in
  54. :language: cmake
  55. When CMake configures this header file the values for
  56. ``@Tutorial_VERSION_MAJOR@`` and ``@Tutorial_VERSION_MINOR@`` will be
  57. replaced.
  58. Next modify ``tutorial.cxx`` to include the configured header file,
  59. ``TutorialConfig.h``.
  60. Finally, let's print out the version number by updating ``tutorial.cxx`` as
  61. follows:
  62. .. literalinclude:: Step2/tutorial.cxx
  63. :language: c++
  64. :start-after: {
  65. :end-before: // convert input to double
  66. Specify the C++ Standard
  67. -------------------------
  68. Next let's add some C++11 features to our project by replacing ``atof`` with
  69. ``std::stod`` in ``tutorial.cxx``. At the same time, remove
  70. ``#include <cstdlib>``.
  71. .. literalinclude:: Step2/tutorial.cxx
  72. :language: c++
  73. :start-after: // convert input to double
  74. :end-before: // calculate square root
  75. We will need to explicitly state in the CMake code that it should use the
  76. correct flags. The easiest way to enable support for a specific C++ standard
  77. in CMake is by using the :variable:`CMAKE_CXX_STANDARD` variable. For this
  78. tutorial, set the :variable:`CMAKE_CXX_STANDARD` variable in the
  79. ``CMakeLists.txt`` file to 11 and :variable:`CMAKE_CXX_STANDARD_REQUIRED` to
  80. True:
  81. .. literalinclude:: Step2/CMakeLists.txt
  82. :language: cmake
  83. :end-before: # configure a header file to pass some of the CMake settings
  84. Build and Test
  85. --------------
  86. Run the :manual:`cmake <cmake(1)>` executable or the
  87. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  88. with your chosen build tool.
  89. For example, from the command line we could navigate to the
  90. ``Help/guide/tutorial`` directory of the CMake source code tree and run the
  91. following commands:
  92. .. code-block:: console
  93. mkdir Step1_build
  94. cd Step1_build
  95. cmake ../Step1
  96. cmake --build .
  97. Navigate to the directory where Tutorial was built (likely the make directory
  98. or a Debug or Release build configuration subdirectory) and run these commands:
  99. .. code-block:: console
  100. Tutorial 4294967296
  101. Tutorial 10
  102. Tutorial
  103. Adding a Library (Step 2)
  104. =========================
  105. Now we will add a library to our project. This library will contain our own
  106. implementation for computing the square root of a number. The executable can
  107. then use this library instead of the standard square root function provided by
  108. the compiler.
  109. For this tutorial we will put the library into a subdirectory
  110. called ``MathFunctions``. This directory already contains a header file,
  111. ``MathFunctions.h``, and a source file ``mysqrt.cxx``. The source file has one
  112. function called ``mysqrt`` that provides similar functionality to the
  113. compiler's ``sqrt`` function.
  114. Add the following one line ``CMakeLists.txt`` file to the ``MathFunctions``
  115. directory:
  116. .. literalinclude:: Step3/MathFunctions/CMakeLists.txt
  117. :language: cmake
  118. To make use of the new library we will add an :command:`add_subdirectory`
  119. call in the top-level ``CMakeLists.txt`` file so that the library will get
  120. built. We add the new library to the executable, and add ``MathFunctions`` as
  121. an include directory so that the ``mqsqrt.h`` header file can be found. The
  122. last few lines of the top-level ``CMakeLists.txt`` file should now look like:
  123. .. code-block:: cmake
  124. # add the MathFunctions library
  125. add_subdirectory(MathFunctions)
  126. # add the executable
  127. add_executable(Tutorial tutorial.cxx)
  128. target_link_libraries(Tutorial PUBLIC MathFunctions)
  129. # add the binary tree to the search path for include files
  130. # so that we will find TutorialConfig.h
  131. target_include_directories(Tutorial PUBLIC
  132. "${PROJECT_BINARY_DIR}"
  133. "${PROJECT_SOURCE_DIR}/MathFunctions"
  134. )
  135. Now let us make the MathFunctions library optional. While for the tutorial
  136. there really isn't any need to do so, for larger projects this is a common
  137. occurrence. The first step is to add an option to the top-level
  138. ``CMakeLists.txt`` file.
  139. .. literalinclude:: Step3/CMakeLists.txt
  140. :language: cmake
  141. :start-after: # should we use our own math functions
  142. :end-before: # add the MathFunctions library
  143. This option will be displayed in the :manual:`cmake-gui <cmake-gui(1)>` and
  144. :manual:`ccmake <ccmake(1)>`
  145. with a default value of ON that can be changed by the user. This setting will
  146. be stored in the cache so that the user does not need to set the value each
  147. time they run CMake on a build directory.
  148. The next change is to make building and linking the MathFunctions library
  149. conditional. To do this we change the end of the top-level ``CMakeLists.txt``
  150. file to look like the following:
  151. .. literalinclude:: Step3/CMakeLists.txt
  152. :language: cmake
  153. :start-after: # add the MathFunctions library
  154. Note the use of the variable ``EXTRA_LIBS`` to collect up any optional
  155. libraries to later be linked into the executable. The variable
  156. ``EXTRA_INCLUDES`` is used similarly for optional header files. This is a
  157. classic approach when dealing with many optional components, we will cover
  158. the modern approach in the next step.
  159. The corresponding changes to the source code are fairly straightforward. First,
  160. in ``tutorial.cxx``, include the ``MathFunctions.h`` header if we need it:
  161. .. literalinclude:: Step3/tutorial.cxx
  162. :language: c++
  163. :start-after: // should we include the MathFunctions header
  164. :end-before: int main
  165. Then, in the same file, make ``USE_MYMATH`` control which square root
  166. function is used:
  167. .. literalinclude:: Step3/tutorial.cxx
  168. :language: c++
  169. :start-after: // which square root function should we use?
  170. :end-before: std::cout << "The square root of
  171. Since the source code now requires ``USE_MYMATH`` we can add it to
  172. ``TutorialConfig.h.in`` with the following line:
  173. .. literalinclude:: Step3/TutorialConfig.h.in
  174. :language: c
  175. :lines: 4
  176. **Exercise**: Why is it important that we configure ``TutorialConfig.h.in``
  177. after the option for ``USE_MYMATH``? What would happen if we inverted the two?
  178. Run the :manual:`cmake <cmake(1)>` executable or the
  179. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  180. with your chosen build tool. Then run the built Tutorial executable.
  181. Use the :manual:`ccmake <ccmake(1)>` executable or the :manual:`cmake-gui <cmake-gui(1)>`
  182. to update the value of ``USE_MYMATH``. Rebuild and run the tutorial again.
  183. Which function gives better results, sqrt or mysqrt?
  184. Adding Usage Requirements for Library (Step 3)
  185. ==============================================
  186. Usage requirements allow for far better control over a library or executable's
  187. link and include line while also giving more control over the transitive
  188. property of targets inside CMake. The primary commands that leverage usage
  189. requirements are:
  190. - :command:`target_compile_definitions`
  191. - :command:`target_compile_options`
  192. - :command:`target_include_directories`
  193. - :command:`target_link_libraries`
  194. Let's refactor our code from `Adding a Library (Step 2)`_ to use the modern
  195. CMake approach of usage requirements. We first state that anybody linking to
  196. MathFunctions needs to include the current source directory, while
  197. MathFunctions itself doesn't. So this can become an ``INTERFACE`` usage
  198. requirement.
  199. Remember ``INTERFACE`` means things that consumers require but the producer
  200. doesn't. Add the following lines to the end of
  201. ``MathFunctions/CMakeLists.txt``:
  202. .. literalinclude:: Step4/MathFunctions/CMakeLists.txt
  203. :language: cmake
  204. :start-after: # to find MathFunctions.h
  205. Now that we've specified usage requirements for MathFunctions we can safely
  206. remove our uses of the ``EXTRA_INCLUDES`` variable from the top-level
  207. ``CMakeLists.txt``, here:
  208. .. literalinclude:: Step4/CMakeLists.txt
  209. :language: cmake
  210. :start-after: # add the MathFunctions library
  211. :end-before: # add the executable
  212. And here:
  213. .. literalinclude:: Step4/CMakeLists.txt
  214. :language: cmake
  215. :start-after: # so that we will find TutorialConfig.h
  216. Once this is done, run the :manual:`cmake <cmake(1)>` executable or the
  217. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  218. with your chosen build tool or by using ``cmake --build .`` from the build
  219. directory.
  220. Installing and Testing (Step 4)
  221. ===============================
  222. Now we can start adding install rules and testing support to our project.
  223. Install Rules
  224. -------------
  225. The install rules are fairly simple: for MathFunctions we want to install the
  226. library and header file and for the application we want to install the
  227. executable and configured header.
  228. So to the end of ``MathFunctions/CMakeLists.txt`` we add:
  229. .. literalinclude:: Step5/MathFunctions/CMakeLists.txt
  230. :language: cmake
  231. :start-after: # install rules
  232. And to the end of the top-level ``CMakeLists.txt`` we add:
  233. .. literalinclude:: Step5/CMakeLists.txt
  234. :language: cmake
  235. :start-after: # add the install targets
  236. :end-before: # enable testing
  237. That is all that is needed to create a basic local install of the tutorial.
  238. Run the :manual:`cmake <cmake(1)>` executable or the
  239. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  240. with your chosen build tool. Run the install step by using the ``install``
  241. option of the :manual:`cmake <cmake(1)>` command (introduced in 3.15, older
  242. versions of CMake must use ``make install``) from the command line, or build
  243. the ``INSTALL`` target from an IDE. This will install the appropriate header
  244. files, libraries, and executables.
  245. The CMake variable :variable:`CMAKE_INSTALL_PREFIX` is used to determine the
  246. root of where the files will be installed. If using ``cmake --install`` a
  247. custom installation directory can be given via the ``--prefix`` argument. For
  248. multi-configuration tools, use the ``--config`` argument to specify the
  249. configuration.
  250. Verify that the installed Tutorial runs.
  251. Testing Support
  252. ---------------
  253. Next let's test our application. At the end of the top-level ``CMakeLists.txt``
  254. file we can enable testing and then add a number of basic tests to verify that
  255. the application is working correctly.
  256. .. literalinclude:: Step5/CMakeLists.txt
  257. :language: cmake
  258. :start-after: # enable testing
  259. The first test simply verifies that the application runs, does not segfault or
  260. otherwise crash, and has a zero return value. This is the basic form of a
  261. CTest test.
  262. The next test makes use of the :prop_test:`PASS_REGULAR_EXPRESSION` test
  263. property to verify that the output of the test contains certain strings. In
  264. this case, verifying that the usage message is printed when an incorrect number
  265. of arguments are provided.
  266. Lastly, we have a function called ``do_test`` that runs the application and
  267. verifies that the computed square root is correct for given input. For each
  268. invocation of ``do_test``, another test is added to the project with a name,
  269. input, and expected results based on the passed arguments.
  270. Rebuild the application and then cd to the binary directory and run the
  271. :manual:`ctest <ctest(1)>` executable: ``ctest -N`` and ``ctest -VV``. For
  272. multi-config generators (e.g. Visual Studio), the configuration type must be
  273. specified. To run tests in Debug mode, for example, use ``ctest -C Debug -VV``
  274. from the build directory (not the Debug subdirectory!). Alternatively, build
  275. the ``RUN_TESTS`` target from the IDE.
  276. Adding System Introspection (Step 5)
  277. ====================================
  278. Let us consider adding some code to our project that depends on features the
  279. target platform may not have. For this example, we will add some code that
  280. depends on whether or not the target platform has the ``log`` and ``exp``
  281. functions. Of course almost every platform has these functions but for this
  282. tutorial assume that they are not common.
  283. If the platform has ``log`` and ``exp`` then we will use them to compute the
  284. square root in the ``mysqrt`` function. We first test for the availability of
  285. these functions using the :module:`CheckSymbolExists` module in the top-level
  286. ``CMakeLists.txt``. On some platforms, we will need to link to the m library.
  287. If ``log`` and ``exp`` are not initially found, require the m library and try
  288. again.
  289. We're going to use the new defines in ``TutorialConfig.h.in``, so be sure to
  290. set them before that file is configured.
  291. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  292. :language: cmake
  293. :start-after: # does this system provide the log and exp functions?
  294. :end-before: # add compile definitions
  295. Now let's add these defines to ``TutorialConfig.h.in`` so that we can use them
  296. from ``mysqrt.cxx``:
  297. .. code-block:: console
  298. // does the platform provide exp and log functions?
  299. #cmakedefine HAVE_LOG
  300. #cmakedefine HAVE_EXP
  301. If ``log`` and ``exp`` are available on the system, then we will use them to
  302. compute the square root in the ``mysqrt`` function. Add the following code to
  303. the ``mysqrt`` function in ``MathFunctions/mysqrt.cxx`` (don't forget the
  304. ``#endif`` before returning the result!):
  305. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  306. :language: c++
  307. :start-after: // if we have both log and exp then use them
  308. :end-before: // do ten iterations
  309. We will also need to modify ``mysqrt.cxx`` to include ``cmath``.
  310. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  311. :language: c++
  312. :end-before: #include <iostream>
  313. Run the :manual:`cmake <cmake(1)>` executable or the
  314. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  315. with your chosen build tool and run the Tutorial executable.
  316. You will notice that we're not using ``log`` and ``exp``, even if we think they
  317. should be available. We should realize quickly that we have forgotten to
  318. include ``TutorialConfig.h`` in ``mysqrt.cxx``.
  319. We will also need to update ``MathFunctions/CMakeLists.txt`` so ``mysqrt.cxx``
  320. knows where this file is located:
  321. .. code-block:: cmake
  322. target_include_directories(MathFunctions
  323. INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
  324. PRIVATE ${CMAKE_BINARY_DIR}
  325. )
  326. After making this update, go ahead and build the project again and run the
  327. built Tutorial executable. If ``log`` and ``exp`` are still not being used,
  328. open the generated ``TutorialConfig.h`` file from the build directory. Maybe
  329. they aren't available on the current system?
  330. Which function gives better results now, sqrt or mysqrt?
  331. Specify Compile Definition
  332. --------------------------
  333. Is there a better place for us to save the ``HAVE_LOG`` and ``HAVE_EXP`` values
  334. other than in ``TutorialConfig.h``? Let's try to use
  335. :command:`target_compile_definitions`.
  336. First, remove the defines from ``TutorialConfig.h.in``. We no longer need to
  337. include ``TutorialConfig.h`` from ``mysqrt.cxx`` or the extra include in
  338. ``MathFunctions/CMakeLists.txt``.
  339. Next, we can move the check for ``HAVE_LOG`` and ``HAVE_EXP`` to
  340. ``MathFunctions/CMakeLists.txt`` and then specify those values as ``PRIVATE``
  341. compile definitions.
  342. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  343. :language: cmake
  344. :start-after: # does this system provide the log and exp functions?
  345. :end-before: # install rules
  346. After making these updates, go ahead and build the project again. Run the
  347. built Tutorial executable and verify that the results are same as earlier in
  348. this step.
  349. Adding a Custom Command and Generated File (Step 6)
  350. ===================================================
  351. Suppose, for the purpose of this tutorial, we decide that we never want to use
  352. the platform ``log`` and ``exp`` functions and instead would like to
  353. generate a table of precomputed values to use in the ``mysqrt`` function.
  354. In this section, we will create the table as part of the build process,
  355. and then compile that table into our application.
  356. First, let's remove the check for the ``log`` and ``exp`` functions in
  357. ``MathFunctions/CMakeLists.txt``. Then remove the check for ``HAVE_LOG`` and
  358. ``HAVE_EXP`` from ``mysqrt.cxx``. At the same time, we can remove
  359. :code:`#include <cmath>`.
  360. In the ``MathFunctions`` subdirectory, a new source file named
  361. ``MakeTable.cxx`` has been provided to generate the table.
  362. After reviewing the file, we can see that the table is produced as valid C++
  363. code and that the output filename is passed in as an argument.
  364. The next step is to add the appropriate commands to the
  365. ``MathFunctions/CMakeLists.txt`` file to build the MakeTable executable and
  366. then run it as part of the build process. A few commands are needed to
  367. accomplish this.
  368. First, at the top of ``MathFunctions/CMakeLists.txt``, the executable for
  369. ``MakeTable`` is added as any other executable would be added.
  370. .. literalinclude:: Step7/MathFunctions/CMakeLists.txt
  371. :language: cmake
  372. :start-after: # first we add the executable that generates the table
  373. :end-before: # add the command to generate the source code
  374. Then we add a custom command that specifies how to produce ``Table.h``
  375. by running MakeTable.
  376. .. literalinclude:: Step7/MathFunctions/CMakeLists.txt
  377. :language: cmake
  378. :start-after: # add the command to generate the source code
  379. :end-before: # add the main library
  380. Next we have to let CMake know that ``mysqrt.cxx`` depends on the generated
  381. file ``Table.h``. This is done by adding the generated ``Table.h`` to the list
  382. of sources for the library MathFunctions.
  383. .. literalinclude:: Step7/MathFunctions/CMakeLists.txt
  384. :language: cmake
  385. :start-after: # add the main library
  386. :end-before: # state that anybody linking
  387. We also have to add the current binary directory to the list of include
  388. directories so that ``Table.h`` can be found and included by ``mysqrt.cxx``.
  389. .. literalinclude:: Step7/MathFunctions/CMakeLists.txt
  390. :start-after: # state that we depend on our bin
  391. :end-before: # install rules
  392. Now let's use the generated table. First, modify ``mysqrt.cxx`` to include
  393. ``Table.h``. Next, we can rewrite the mysqrt function to use the table:
  394. .. literalinclude:: Step7/MathFunctions/mysqrt.cxx
  395. :language: c++
  396. :start-after: // a hack square root calculation using simple operations
  397. Run the :manual:`cmake <cmake(1)>` executable or the
  398. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  399. with your chosen build tool.
  400. When this project is built it will first build the ``MakeTable`` executable.
  401. It will then run ``MakeTable`` to produce ``Table.h``. Finally, it will
  402. compile ``mysqrt.cxx`` which includes ``Table.h`` to produce the MathFunctions
  403. library.
  404. Run the Tutorial executable and verify that it is using the table.
  405. Building an Installer (Step 7)
  406. ==============================
  407. Next suppose that we want to distribute our project to other people so that
  408. they can use it. We want to provide both binary and source distributions on a
  409. variety of platforms. This is a little different from the install we did
  410. previously in `Installing and Testing (Step 4)`_ , where we were
  411. installing the binaries that we had built from the source code. In this
  412. example we will be building installation packages that support binary
  413. installations and package management features. To accomplish this we will use
  414. CPack to create platform specific installers. Specifically we need to add a
  415. few lines to the bottom of our top-level ``CMakeLists.txt`` file.
  416. .. literalinclude:: Step8/CMakeLists.txt
  417. :language: cmake
  418. :start-after: # setup installer
  419. That is all there is to it. We start by including
  420. :module:`InstallRequiredSystemLibraries`. This module will include any runtime
  421. libraries that are needed by the project for the current platform. Next we set
  422. some CPack variables to where we have stored the license and version
  423. information for this project. The version information was set earlier in this
  424. tutorial and the ``license.txt`` has been included in the top-level source
  425. directory for this step.
  426. Finally we include the :module:`CPack module <CPack>` which will use these
  427. variables and some other properties of the current system to setup an
  428. installer.
  429. The next step is to build the project in the usual manner and then run the
  430. :manual:`cpack <cpack(1)>` executable. To build a binary distribution, from the
  431. binary directory run:
  432. .. code-block:: console
  433. cpack
  434. To specify the generator, use the ``-G`` option. For multi-config builds, use
  435. ``-C`` to specify the configuration. For example:
  436. .. code-block:: console
  437. cpack -G ZIP -C Debug
  438. To create a source distribution you would type:
  439. .. code-block:: console
  440. cpack --config CPackSourceConfig.cmake
  441. Alternatively, run ``make package`` or right click the ``Package`` target and
  442. ``Build Project`` from an IDE.
  443. Run the installer found in the binary directory. Then run the installed
  444. executable and verify that it works.
  445. Adding Support for a Dashboard (Step 8)
  446. =======================================
  447. Adding support for submitting our test results to a dashboard is simple. We
  448. already defined a number of tests for our project in `Testing Support`_. Now we
  449. just have to run those tests and submit them to a dashboard. To include support
  450. for dashboards we include the :module:`CTest` module in our top-level
  451. ``CMakeLists.txt``.
  452. Replace:
  453. .. code-block:: cmake
  454. # enable testing
  455. enable_testing()
  456. With:
  457. .. code-block:: cmake
  458. # enable dashboard scripting
  459. include(CTest)
  460. The :module:`CTest` module will automatically call ``enable_testing()``, so we
  461. can remove it from our CMake files.
  462. We will also need to create a ``CTestConfig.cmake`` file in the top-level
  463. directory where we can specify the name of the project and where to submit the
  464. dashboard.
  465. .. literalinclude:: Step9/CTestConfig.cmake
  466. :language: cmake
  467. The :manual:`ctest <ctest(1)>` executable will read in this file when it runs.
  468. To create a simple dashboard you can run the :manual:`cmake <cmake(1)>`
  469. executable or the :manual:`cmake-gui <cmake-gui(1)>` to configure the project,
  470. but do not build it yet. Instead, change directory to the binary tree, and then
  471. run:
  472. ctest [-VV] -D Experimental
  473. Remember, for multi-config generators (e.g. Visual Studio), the configuration
  474. type must be specified::
  475. ctest [-VV] -C Debug -D Experimental
  476. Or, from an IDE, build the ``Experimental`` target.
  477. The :manual:`ctest <ctest(1)>` executable will build and test the project and
  478. submit the results to Kitware's public dashboard:
  479. https://my.cdash.org/index.php?project=CMakeTutorial.
  480. Mixing Static and Shared (Step 9)
  481. =================================
  482. In this section we will show how the :variable:`BUILD_SHARED_LIBS` variable can
  483. be used to control the default behavior of :command:`add_library`,
  484. and allow control over how libraries without an explicit type (``STATIC``,
  485. ``SHARED``, ``MODULE`` or ``OBJECT``) are built.
  486. To accomplish this we need to add :variable:`BUILD_SHARED_LIBS` to the
  487. top-level ``CMakeLists.txt``. We use the :command:`option` command as it allows
  488. users to optionally select if the value should be ON or OFF.
  489. Next we are going to refactor MathFunctions to become a real library that
  490. encapsulates using ``mysqrt`` or ``sqrt``, instead of requiring the calling
  491. code to do this logic. This will also mean that ``USE_MYMATH`` will not control
  492. building MathFunctions, but instead will control the behavior of this library.
  493. The first step is to update the starting section of the top-level
  494. ``CMakeLists.txt`` to look like:
  495. .. literalinclude:: Step10/CMakeLists.txt
  496. :language: cmake
  497. :end-before: # add the binary tree
  498. Now that we have made MathFunctions always be used, we will need to update
  499. the logic of that library. So, in ``MathFunctions/CMakeLists.txt`` we need to
  500. create a SqrtLibrary that will conditionally be built when ``USE_MYMATH`` is
  501. enabled. Now, since this is a tutorial, we are going to explicitly require
  502. that SqrtLibrary is built statically.
  503. The end result is that ``MathFunctions/CMakeLists.txt`` should look like:
  504. .. literalinclude:: Step10/MathFunctions/CMakeLists.txt
  505. :language: cmake
  506. :lines: 1-36,42-
  507. Next, update ``MathFunctions/mysqrt.cxx`` to use the ``mathfunctions`` and
  508. ``detail`` namespaces:
  509. .. literalinclude:: Step10/MathFunctions/mysqrt.cxx
  510. :language: c++
  511. We also need to make some changes in ``tutorial.cxx``, so that it no longer
  512. uses ``USE_MYMATH``:
  513. #. Always include ``MathFunctions.h``
  514. #. Always use ``mathfunctions::sqrt``
  515. #. Don't include cmath
  516. Finally, update ``MathFunctions/MathFunctions.h`` to use dll export defines:
  517. .. literalinclude:: Step10/MathFunctions/MathFunctions.h
  518. :language: c++
  519. At this point, if you build everything, you may notice that linking fails
  520. as we are combining a static library without position independent code with a
  521. library that has position independent code. The solution to this is to
  522. explicitly set the :prop_tgt:`POSITION_INDEPENDENT_CODE` target property of
  523. SqrtLibrary to be True no matter the build type.
  524. .. literalinclude:: Step10/MathFunctions/CMakeLists.txt
  525. :language: cmake
  526. :lines: 37-42
  527. **Exercise**: We modified ``MathFunctions.h`` to use dll export defines.
  528. Using CMake documentation can you find a helper module to simplify this?
  529. Adding Generator Expressions (Step 10)
  530. ======================================
  531. :manual:`Generator expressions <cmake-generator-expressions(7)>` are evaluated
  532. during build system generation to produce information specific to each build
  533. configuration.
  534. :manual:`Generator expressions <cmake-generator-expressions(7)>` are allowed in
  535. the context of many target properties, such as :prop_tgt:`LINK_LIBRARIES`,
  536. :prop_tgt:`INCLUDE_DIRECTORIES`, :prop_tgt:`COMPILE_DEFINITIONS` and others.
  537. They may also be used when using commands to populate those properties, such as
  538. :command:`target_link_libraries`, :command:`target_include_directories`,
  539. :command:`target_compile_definitions` and others.
  540. :manual:`Generator expressions <cmake-generator-expressions(7)>` may be used
  541. to enable conditional linking, conditional definitions used when compiling,
  542. conditional include directories and more. The conditions may be based on the
  543. build configuration, target properties, platform information or any other
  544. queryable information.
  545. There are different types of
  546. :manual:`generator expressions <cmake-generator-expressions(7)>` including
  547. Logical, Informational, and Output expressions.
  548. Logical expressions are used to create conditional output. The basic
  549. expressions are the 0 and 1 expressions. A ``$<0:...>`` results in the empty
  550. string, and ``<1:...>`` results in the content of "...". They can also be
  551. nested.
  552. A common usage of
  553. :manual:`generator expressions <cmake-generator-expressions(7)>` is to
  554. conditionally add compiler flags, such as those for language levels or
  555. warnings. A nice pattern is to associate this information to an ``INTERFACE``
  556. target allowing this information to propagate. Lets start by constructing an
  557. ``INTERFACE`` target and specifying the required C++ standard level of ``11``
  558. instead of using :variable:`CMAKE_CXX_STANDARD`.
  559. So the following code:
  560. .. literalinclude:: Step10/CMakeLists.txt
  561. :language: cmake
  562. :start-after: project(Tutorial VERSION 1.0)
  563. :end-before: # control where the static and shared libraries are built so that on windows
  564. Would be replaced with:
  565. .. literalinclude:: Step11/CMakeLists.txt
  566. :language: cmake
  567. :start-after: project(Tutorial VERSION 1.0)
  568. :end-before: # add compiler warning flags just when building this project via
  569. Next we add the desired compiler warning flags that we want for our project. As
  570. warning flags vary based on the compiler we use the ``COMPILE_LANG_AND_ID``
  571. generator expression to control which flags to apply given a language and a set
  572. of compiler ids as seen below:
  573. .. literalinclude:: Step11/CMakeLists.txt
  574. :language: cmake
  575. :start-after: # the BUILD_INTERFACE genex
  576. :end-before: # control where the static and shared libraries are built so that on windows
  577. Looking at this we see that the warning flags are encapsulated inside a
  578. ``BUILD_INTERFACE`` condition. This is done so that consumers of our installed
  579. project will not inherit our warning flags.
  580. **Exercise**: Modify ``MathFunctions/CMakeLists.txt`` so that all targets have
  581. a :command:`target_link_libraries` call to ``tutorial_compiler_flags``.
  582. Adding Export Configuration (Step 11)
  583. =====================================
  584. During `Installing and Testing (Step 4)`_ of the tutorial we added the ability
  585. for CMake to install the library and headers of the project. During
  586. `Building an Installer (Step 7)`_ we added the ability to package up this
  587. information so it could be distributed to other people.
  588. The next step is to add the necessary information so that other CMake projects
  589. can use our project, be it from a build directory, a local install or when
  590. packaged.
  591. The first step is to update our :command:`install(TARGETS)` commands to not
  592. only specify a ``DESTINATION`` but also an ``EXPORT``. The ``EXPORT`` keyword
  593. generates and installs a CMake file containing code to import all targets
  594. listed in the install command from the installation tree. So let's go ahead and
  595. explicitly ``EXPORT`` the MathFunctions library by updating the ``install``
  596. command in ``MathFunctions/CMakeLists.txt`` to look like:
  597. .. literalinclude:: Complete/MathFunctions/CMakeLists.txt
  598. :language: cmake
  599. :start-after: # install rules
  600. Now that we have MathFunctions being exported, we also need to explicitly
  601. install the generated ``MathFunctionsTargets.cmake`` file. This is done by
  602. adding the following to the bottom of the top-level ``CMakeLists.txt``:
  603. .. literalinclude:: Complete/CMakeLists.txt
  604. :language: cmake
  605. :start-after: # install the configuration targets
  606. :end-before: include(CMakePackageConfigHelpers)
  607. At this point you should try and run CMake. If everything is setup properly
  608. you will see that CMake will generate an error that looks like:
  609. .. code-block:: console
  610. Target "MathFunctions" INTERFACE_INCLUDE_DIRECTORIES property contains
  611. path:
  612. "/Users/robert/Documents/CMakeClass/Tutorial/Step11/MathFunctions"
  613. which is prefixed in the source directory.
  614. What CMake is trying to say is that during generating the export information
  615. it will export a path that is intrinsically tied to the current machine and
  616. will not be valid on other machines. The solution to this is to update the
  617. MathFunctions :command:`target_include_directories` to understand that it needs
  618. different ``INTERFACE`` locations when being used from within the build
  619. directory and from an install / package. This means converting the
  620. :command:`target_include_directories` call for MathFunctions to look like:
  621. .. literalinclude:: Step12/MathFunctions/CMakeLists.txt
  622. :language: cmake
  623. :start-after: # to find MathFunctions.h, while we don't.
  624. :end-before: # should we use our own math functions
  625. Once this has been updated, we can re-run CMake and verify that it doesn't
  626. warn anymore.
  627. At this point, we have CMake properly packaging the target information that is
  628. required but we will still need to generate a ``MathFunctionsConfig.cmake`` so
  629. that the CMake :command:`find_package` command can find our project. So let's go
  630. ahead and add a new file to the top-level of the project called
  631. ``Config.cmake.in`` with the following contents:
  632. .. literalinclude:: Step12/Config.cmake.in
  633. Then, to properly configure and install that file, add the following to the
  634. bottom of the top-level ``CMakeLists.txt``:
  635. .. literalinclude:: Step12/CMakeLists.txt
  636. :language: cmake
  637. :start-after: # install the configuration targets
  638. :end-before: # generate the export
  639. At this point, we have generated a relocatable CMake Configuration for our
  640. project that can be used after the project has been installed or packaged. If
  641. we want our project to also be used from a build directory we only have to add
  642. the following to the bottom of the top level ``CMakeLists.txt``:
  643. .. literalinclude:: Step12/CMakeLists.txt
  644. :language: cmake
  645. :start-after: # needs to be after the install(TARGETS ) command
  646. With this export call we now generate a ``Targets.cmake``, allowing the
  647. configured ``MathFunctionsConfig.cmake`` in the build directory to be used by
  648. other projects, without needing it to be installed.
  649. Packaging Debug and Release (Step 12)
  650. =====================================
  651. **Note:** This example is valid for single-configuration generators and will
  652. not work for multi-configuration generators (e.g. Visual Studio).
  653. By default, CMake's model is that a build directory only contains a single
  654. configuration, be it Debug, Release, MinSizeRel, or RelWithDebInfo. It is
  655. possible, however, to setup CPack to bundle multiple build directories and
  656. construct a package that contains multiple configurations of the same project.
  657. First, we want to ensure that the debug and release builds use different names
  658. for the executables and libraries that will be installed. Let's use `d` as the
  659. postfix for the debug executable and libraries.
  660. Set :variable:`CMAKE_DEBUG_POSTFIX` near the beginning of the top-level
  661. ``CMakeLists.txt`` file:
  662. .. literalinclude:: Complete/CMakeLists.txt
  663. :language: cmake
  664. :start-after: project(Tutorial VERSION 1.0)
  665. :end-before: target_compile_features(tutorial_compiler_flags
  666. And the :prop_tgt:`DEBUG_POSTFIX` property on the tutorial executable:
  667. .. literalinclude:: Complete/CMakeLists.txt
  668. :language: cmake
  669. :start-after: # add the executable
  670. :end-before: # add the binary tree to the search path for include files
  671. Let's also add version numbering to the MathFunctions library. In
  672. ``MathFunctions/CMakeLists.txt``, set the :prop_tgt:`VERSION` and
  673. :prop_tgt:`SOVERSION` properties:
  674. .. literalinclude:: Complete/MathFunctions/CMakeLists.txt
  675. :language: cmake
  676. :start-after: # setup the version numbering
  677. :end-before: # install rules
  678. From the ``Step12`` directory, create ``debug`` and ``release``
  679. subbdirectories. The layout will look like:
  680. .. code-block:: none
  681. - Step12
  682. - debug
  683. - release
  684. Now we need to setup debug and release builds. We can use
  685. :variable:`CMAKE_BUILD_TYPE` to set the configuration type:
  686. .. code-block:: console
  687. cd debug
  688. cmake -DCMAKE_BUILD_TYPE=Debug ..
  689. cmake --build .
  690. cd ../release
  691. cmake -DCMAKE_BUILD_TYPE=Release ..
  692. cmake --build .
  693. Now that both the debug and release builds are complete, we can use a custom
  694. configuration file to package both builds into a single release. In the
  695. ``Step12`` directory, create a file called ``MultiCPackConfig.cmake``. In this
  696. file, first include the default configuration file that was created by the
  697. :manual:`cmake <cmake(1)>` executable.
  698. Next, use the ``CPACK_INSTALL_CMAKE_PROJECTS`` variable to specify which
  699. projects to install. In this case, we want to install both debug and release.
  700. .. literalinclude:: Complete/MultiCPackConfig.cmake
  701. :language: cmake
  702. From the ``Step12`` directory, run :manual:`cpack <cpack(1)>` specifying our
  703. custom configuration file with the ``config`` option:
  704. .. code-block:: console
  705. cpack --config MultiCPackConfig.cmake