index.rst 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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``. We're going to use the new defines in
  287. ``TutorialConfig.h.in``, so be sure to set them before that file is configured.
  288. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  289. :language: cmake
  290. :start-after: # does this system provide the log and exp functions?
  291. :end-before: if(HAVE_LOG AND HAVE_EXP)
  292. Now let's add these defines to ``TutorialConfig.h.in`` so that we can use them
  293. from ``mysqrt.cxx``:
  294. .. code-block:: console
  295. // does the platform provide exp and log functions?
  296. #cmakedefine HAVE_LOG
  297. #cmakedefine HAVE_EXP
  298. If ``log`` and ``exp`` are available on the system, then we will use them to
  299. compute the square root in the ``mysqrt`` function. Add the following code to
  300. the ``mysqrt`` function in ``MathFunctions/mysqrt.cxx`` (don't forget the
  301. ``#endif`` before returning the result!):
  302. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  303. :language: c++
  304. :start-after: // if we have both log and exp then use them
  305. :end-before: // do ten iterations
  306. We will also need to modify ``mysqrt.cxx`` to include ``cmath``.
  307. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  308. :language: c++
  309. :end-before: #include <iostream>
  310. Run the :manual:`cmake <cmake(1)>` executable or the
  311. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  312. with your chosen build tool and run the Tutorial executable.
  313. You will notice that we're not using ``log`` and ``exp``, even if we think they
  314. should be available. We should realize quickly that we have forgotten to
  315. include ``TutorialConfig.h`` in ``mysqrt.cxx``.
  316. We will also need to update ``MathFunctions/CMakeLists.txt`` so ``mysqrt.cxx``
  317. knows where this file is located:
  318. .. code-block:: cmake
  319. target_include_directories(MathFunctions
  320. INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}
  321. PRIVATE ${CMAKE_BINARY_DIR}
  322. )
  323. After making this update, go ahead and build the project again and run the
  324. built Tutorial executable. If ``log`` and ``exp`` are still not being used,
  325. open the generated ``TutorialConfig.h`` file from the build directory. Maybe
  326. they aren't available on the current system?
  327. Which function gives better results now, sqrt or mysqrt?
  328. Specify Compile Definition
  329. --------------------------
  330. Is there a better place for us to save the ``HAVE_LOG`` and ``HAVE_EXP`` values
  331. other than in ``TutorialConfig.h``? Let's try to use
  332. :command:`target_compile_definitions`.
  333. First, remove the defines from ``TutorialConfig.h.in``. We no longer need to
  334. include ``TutorialConfig.h`` from ``mysqrt.cxx`` or the extra include in
  335. ``MathFunctions/CMakeLists.txt``.
  336. Next, we can move the check for ``HAVE_LOG`` and ``HAVE_EXP`` to
  337. ``MathFunctions/CMakeLists.txt`` and then specify those values as ``PRIVATE``
  338. compile definitions.
  339. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  340. :language: cmake
  341. :start-after: # does this system provide the log and exp functions?
  342. :end-before: # install rules
  343. After making these updates, go ahead and build the project again. Run the
  344. built Tutorial executable and verify that the results are same as earlier in
  345. this step.
  346. Adding a Custom Command and Generated File (Step 6)
  347. ===================================================
  348. Suppose, for the purpose of this tutorial, we decide that we never want to use
  349. the platform ``log`` and ``exp`` functions and instead would like to
  350. generate a table of precomputed values to use in the ``mysqrt`` function.
  351. In this section, we will create the table as part of the build process,
  352. and then compile that table into our application.
  353. First, let's remove the check for the ``log`` and ``exp`` functions in
  354. ``MathFunctions/CMakeLists.txt``. Then remove the check for ``HAVE_LOG`` and
  355. ``HAVE_EXP`` from ``mysqrt.cxx``. At the same time, we can remove
  356. :code:`#include <cmath>`.
  357. In the ``MathFunctions`` subdirectory, a new source file named
  358. ``MakeTable.cxx`` has been provided to generate the table.
  359. After reviewing the file, we can see that the table is produced as valid C++
  360. code and that the output filename is passed in as an argument.
  361. The next step is to add the appropriate commands to the
  362. ``MathFunctions/CMakeLists.txt`` file to build the MakeTable executable and
  363. then run it as part of the build process. A few commands are needed to
  364. accomplish this.
  365. First, at the top of ``MathFunctions/CMakeLists.txt``, the executable for
  366. ``MakeTable`` is added as any other executable would be added.
  367. .. literalinclude:: Step7/MathFunctions/CMakeLists.txt
  368. :language: cmake
  369. :start-after: # first we add the executable that generates the table
  370. :end-before: # add the command to generate the source code
  371. Then we add a custom command that specifies how to produce ``Table.h``
  372. by running MakeTable.
  373. .. literalinclude:: Step7/MathFunctions/CMakeLists.txt
  374. :language: cmake
  375. :start-after: # add the command to generate the source code
  376. :end-before: # add the main library
  377. Next we have to let CMake know that ``mysqrt.cxx`` depends on the generated
  378. file ``Table.h``. This is done by adding the generated ``Table.h`` to the list
  379. of sources for the library MathFunctions.
  380. .. literalinclude:: Step7/MathFunctions/CMakeLists.txt
  381. :language: cmake
  382. :start-after: # add the main library
  383. :end-before: # state that anybody linking
  384. We also have to add the current binary directory to the list of include
  385. directories so that ``Table.h`` can be found and included by ``mysqrt.cxx``.
  386. .. literalinclude:: Step7/MathFunctions/CMakeLists.txt
  387. :start-after: # state that we depend on our bin
  388. :end-before: # install rules
  389. Now let's use the generated table. First, modify ``mysqrt.cxx`` to include
  390. ``Table.h``. Next, we can rewrite the mysqrt function to use the table:
  391. .. literalinclude:: Step7/MathFunctions/mysqrt.cxx
  392. :language: c++
  393. :start-after: // a hack square root calculation using simple operations
  394. Run the :manual:`cmake <cmake(1)>` executable or the
  395. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  396. with your chosen build tool.
  397. When this project is built it will first build the ``MakeTable`` executable.
  398. It will then run ``MakeTable`` to produce ``Table.h``. Finally, it will
  399. compile ``mysqrt.cxx`` which includes ``Table.h`` to produce the MathFunctions
  400. library.
  401. Run the Tutorial executable and verify that it is using the table.
  402. Building an Installer (Step 7)
  403. ==============================
  404. Next suppose that we want to distribute our project to other people so that
  405. they can use it. We want to provide both binary and source distributions on a
  406. variety of platforms. This is a little different from the install we did
  407. previously in `Installing and Testing (Step 4)`_ , where we were
  408. installing the binaries that we had built from the source code. In this
  409. example we will be building installation packages that support binary
  410. installations and package management features. To accomplish this we will use
  411. CPack to create platform specific installers. Specifically we need to add a
  412. few lines to the bottom of our top-level ``CMakeLists.txt`` file.
  413. .. literalinclude:: Step8/CMakeLists.txt
  414. :language: cmake
  415. :start-after: # setup installer
  416. That is all there is to it. We start by including
  417. :module:`InstallRequiredSystemLibraries`. This module will include any runtime
  418. libraries that are needed by the project for the current platform. Next we set
  419. some CPack variables to where we have stored the license and version
  420. information for this project. The version information was set earlier in this
  421. tutorial and the ``license.txt`` has been included in the top-level source
  422. directory for this step.
  423. Finally we include the :module:`CPack module <CPack>` which will use these
  424. variables and some other properties of the current system to setup an
  425. installer.
  426. The next step is to build the project in the usual manner and then run the
  427. :manual:`cpack <cpack(1)>` executable. To build a binary distribution, from the
  428. binary directory run:
  429. .. code-block:: console
  430. cpack
  431. To specify the generator, use the ``-G`` option. For multi-config builds, use
  432. ``-C`` to specify the configuration. For example:
  433. .. code-block:: console
  434. cpack -G ZIP -C Debug
  435. To create a source distribution you would type:
  436. .. code-block:: console
  437. cpack --config CPackSourceConfig.cmake
  438. Alternatively, run ``make package`` or right click the ``Package`` target and
  439. ``Build Project`` from an IDE.
  440. Run the installer found in the binary directory. Then run the installed
  441. executable and verify that it works.
  442. Adding Support for a Dashboard (Step 8)
  443. =======================================
  444. Adding support for submitting our test results to a dashboard is simple. We
  445. already defined a number of tests for our project in `Testing Support`_. Now we
  446. just have to run those tests and submit them to a dashboard. To include support
  447. for dashboards we include the :module:`CTest` module in our top-level
  448. ``CMakeLists.txt``.
  449. Replace:
  450. .. code-block:: cmake
  451. # enable testing
  452. enable_testing()
  453. With:
  454. .. code-block:: cmake
  455. # enable dashboard scripting
  456. include(CTest)
  457. The :module:`CTest` module will automatically call ``enable_testing()``, so we
  458. can remove it from our CMake files.
  459. We will also need to create a ``CTestConfig.cmake`` file in the top-level
  460. directory where we can specify the name of the project and where to submit the
  461. dashboard.
  462. .. literalinclude:: Step9/CTestConfig.cmake
  463. :language: cmake
  464. The :manual:`ctest <ctest(1)>` executable will read in this file when it runs.
  465. To create a simple dashboard you can run the :manual:`cmake <cmake(1)>`
  466. executable or the :manual:`cmake-gui <cmake-gui(1)>` to configure the project,
  467. but do not build it yet. Instead, change directory to the binary tree, and then
  468. run:
  469. ctest [-VV] -D Experimental
  470. Remember, for multi-config generators (e.g. Visual Studio), the configuration
  471. type must be specified::
  472. ctest [-VV] -C Debug -D Experimental
  473. Or, from an IDE, build the ``Experimental`` target.
  474. The :manual:`ctest <ctest(1)>` executable will build and test the project and
  475. submit the results to Kitware's public dashboard:
  476. https://my.cdash.org/index.php?project=CMakeTutorial.
  477. Mixing Static and Shared (Step 9)
  478. =================================
  479. In this section we will show how the :variable:`BUILD_SHARED_LIBS` variable can
  480. be used to control the default behavior of :command:`add_library`,
  481. and allow control over how libraries without an explicit type (``STATIC``,
  482. ``SHARED``, ``MODULE`` or ``OBJECT``) are built.
  483. To accomplish this we need to add :variable:`BUILD_SHARED_LIBS` to the
  484. top-level ``CMakeLists.txt``. We use the :command:`option` command as it allows
  485. users to optionally select if the value should be ON or OFF.
  486. Next we are going to refactor MathFunctions to become a real library that
  487. encapsulates using ``mysqrt`` or ``sqrt``, instead of requiring the calling
  488. code to do this logic. This will also mean that ``USE_MYMATH`` will not control
  489. building MathFunctions, but instead will control the behavior of this library.
  490. The first step is to update the starting section of the top-level
  491. ``CMakeLists.txt`` to look like:
  492. .. literalinclude:: Step10/CMakeLists.txt
  493. :language: cmake
  494. :end-before: # add the binary tree
  495. Now that we have made MathFunctions always be used, we will need to update
  496. the logic of that library. So, in ``MathFunctions/CMakeLists.txt`` we need to
  497. create a SqrtLibrary that will conditionally be built when ``USE_MYMATH`` is
  498. enabled. Now, since this is a tutorial, we are going to explicitly require
  499. that SqrtLibrary is built statically.
  500. The end result is that ``MathFunctions/CMakeLists.txt`` should look like:
  501. .. literalinclude:: Step10/MathFunctions/CMakeLists.txt
  502. :language: cmake
  503. :lines: 1-36,42-
  504. Next, update ``MathFunctions/mysqrt.cxx`` to use the ``mathfunctions`` and
  505. ``detail`` namespaces:
  506. .. literalinclude:: Step10/MathFunctions/mysqrt.cxx
  507. :language: c++
  508. We also need to make some changes in ``tutorial.cxx``, so that it no longer
  509. uses ``USE_MYMATH``:
  510. #. Always include ``MathFunctions.h``
  511. #. Always use ``mathfunctions::sqrt``
  512. #. Don't include cmath
  513. Finally, update ``MathFunctions/MathFunctions.h`` to use dll export defines:
  514. .. literalinclude:: Step10/MathFunctions/MathFunctions.h
  515. :language: c++
  516. At this point, if you build everything, you will notice that linking fails
  517. as we are combining a static library without position independent code with a
  518. library that has position independent code. The solution to this is to
  519. explicitly set the :prop_tgt:`POSITION_INDEPENDENT_CODE` target property of
  520. SqrtLibrary to be True no matter the build type.
  521. .. literalinclude:: Step10/MathFunctions/CMakeLists.txt
  522. :language: cmake
  523. :lines: 37-42
  524. **Exercise**: We modified ``MathFunctions.h`` to use dll export defines.
  525. Using CMake documentation can you find a helper module to simplify this?
  526. Adding Generator Expressions (Step 10)
  527. ======================================
  528. :manual:`Generator expressions <cmake-generator-expressions(7)>` are evaluated
  529. during build system generation to produce information specific to each build
  530. configuration.
  531. :manual:`Generator expressions <cmake-generator-expressions(7)>` are allowed in
  532. the context of many target properties, such as :prop_tgt:`LINK_LIBRARIES`,
  533. :prop_tgt:`INCLUDE_DIRECTORIES`, :prop_tgt:`COMPILE_DEFINITIONS` and others.
  534. They may also be used when using commands to populate those properties, such as
  535. :command:`target_link_libraries`, :command:`target_include_directories`,
  536. :command:`target_compile_definitions` and others.
  537. :manual:`Generator expressions <cmake-generator-expressions(7)>` may be used
  538. to enable conditional linking, conditional definitions used when compiling,
  539. conditional include directories and more. The conditions may be based on the
  540. build configuration, target properties, platform information or any other
  541. queryable information.
  542. There are different types of
  543. :manual:`generator expressions <cmake-generator-expressions(7)>` including
  544. Logical, Informational, and Output expressions.
  545. Logical expressions are used to create conditional output. The basic
  546. expressions are the 0 and 1 expressions. A ``$<0:...>`` results in the empty
  547. string, and ``<1:...>`` results in the content of "...". They can also be
  548. nested.
  549. A common usage of
  550. :manual:`generator expressions <cmake-generator-expressions(7)>` is to
  551. conditionally add compiler flags, such as those for language levels or
  552. warnings. A nice pattern is to associate this information to an ``INTERFACE``
  553. target allowing this information to propagate. Lets start by constructing an
  554. ``INTERFACE`` target and specifying the required C++ standard level of ``11``
  555. instead of using :variable:`CMAKE_CXX_STANDARD`.
  556. So the following code:
  557. .. literalinclude:: Step10/CMakeLists.txt
  558. :language: cmake
  559. :start-after: project(Tutorial VERSION 1.0)
  560. :end-before: # control where the static and shared libraries are built so that on windows
  561. Would be replaced with:
  562. .. literalinclude:: Step11/CMakeLists.txt
  563. :language: cmake
  564. :start-after: project(Tutorial VERSION 1.0)
  565. :end-before: # add compiler warning flags just when building this project via
  566. Next we add the desired compiler warning flags that we want for our project. As
  567. warning flags vary based on the compiler we use the ``COMPILE_LANG_AND_ID``
  568. generator expression to control which flags to apply given a language and a set
  569. of compiler ids as seen below:
  570. .. literalinclude:: Step11/CMakeLists.txt
  571. :language: cmake
  572. :start-after: # the BUILD_INTERFACE genex
  573. :end-before: # control where the static and shared libraries are built so that on windows
  574. Looking at this we see that the warning flags are encapsulated inside a
  575. ``BUILD_INTERFACE`` condition. This is done so that consumers of our installed
  576. project will not inherit our warning flags.
  577. **Exercise**: Modify ``MathFunctions/CMakeLists.txt`` so that all targets have
  578. a :command:`target_link_libraries` call to ``tutorial_compiler_flags``.
  579. Adding Export Configuration (Step 11)
  580. =====================================
  581. During `Installing and Testing (Step 4)`_ of the tutorial we added the ability
  582. for CMake to install the library and headers of the project. During
  583. `Building an Installer (Step 7)`_ we added the ability to package up this
  584. information so it could be distributed to other people.
  585. The next step is to add the necessary information so that other CMake projects
  586. can use our project, be it from a build directory, a local install or when
  587. packaged.
  588. The first step is to update our :command:`install(TARGETS)` commands to not
  589. only specify a ``DESTINATION`` but also an ``EXPORT``. The ``EXPORT`` keyword
  590. generates and installs a CMake file containing code to import all targets
  591. listed in the install command from the installation tree. So let's go ahead and
  592. explicitly ``EXPORT`` the MathFunctions library by updating the ``install``
  593. command in ``MathFunctions/CMakeLists.txt`` to look like:
  594. .. literalinclude:: Complete/MathFunctions/CMakeLists.txt
  595. :language: cmake
  596. :start-after: # install rules
  597. Now that we have MathFunctions being exported, we also need to explicitly
  598. install the generated ``MathFunctionsTargets.cmake`` file. This is done by
  599. adding the following to the bottom of the top-level ``CMakeLists.txt``:
  600. .. literalinclude:: Complete/CMakeLists.txt
  601. :language: cmake
  602. :start-after: # install the configuration targets
  603. :end-before: include(CMakePackageConfigHelpers)
  604. At this point you should try and run CMake. If everything is setup properly
  605. you will see that CMake will generate an error that looks like:
  606. .. code-block:: console
  607. Target "MathFunctions" INTERFACE_INCLUDE_DIRECTORIES property contains
  608. path:
  609. "/Users/robert/Documents/CMakeClass/Tutorial/Step11/MathFunctions"
  610. which is prefixed in the source directory.
  611. What CMake is trying to say is that during generating the export information
  612. it will export a path that is intrinsically tied to the current machine and
  613. will not be valid on other machines. The solution to this is to update the
  614. MathFunctions :command:`target_include_directories` to understand that it needs
  615. different ``INTERFACE`` locations when being used from within the build
  616. directory and from an install / package. This means converting the
  617. :command:`target_include_directories` call for MathFunctions to look like:
  618. .. literalinclude:: Step12/MathFunctions/CMakeLists.txt
  619. :language: cmake
  620. :start-after: # to find MathFunctions.h, while we don't.
  621. :end-before: # should we use our own math functions
  622. Once this has been updated, we can re-run CMake and verify that it doesn't
  623. warn anymore.
  624. At this point, we have CMake properly packaging the target information that is
  625. required but we will still need to generate a ``MathFunctionsConfig.cmake`` so
  626. that the CMake :command:`find_package` command can find our project. So let's go
  627. ahead and add a new file to the top-level of the project called
  628. ``Config.cmake.in`` with the following contents:
  629. .. literalinclude:: Step12/Config.cmake.in
  630. Then, to properly configure and install that file, add the following to the
  631. bottom of the top-level ``CMakeLists.txt``:
  632. .. literalinclude:: Step12/CMakeLists.txt
  633. :language: cmake
  634. :start-after: # install the configuration targets
  635. :end-before: # generate the export
  636. At this point, we have generated a relocatable CMake Configuration for our
  637. project that can be used after the project has been installed or packaged. If
  638. we want our project to also be used from a build directory we only have to add
  639. the following to the bottom of the top level ``CMakeLists.txt``:
  640. .. literalinclude:: Step12/CMakeLists.txt
  641. :language: cmake
  642. :start-after: # needs to be after the install(TARGETS ) command
  643. With this export call we now generate a ``Targets.cmake``, allowing the
  644. configured ``MathFunctionsConfig.cmake`` in the build directory to be used by
  645. other projects, without needing it to be installed.
  646. Packaging Debug and Release (Step 12)
  647. =====================================
  648. **Note:** This example is valid for single-configuration generators and will
  649. not work for multi-configuration generators (e.g. Visual Studio).
  650. By default, CMake's model is that a build directory only contains a single
  651. configuration, be it Debug, Release, MinSizeRel, or RelWithDebInfo. It is
  652. possible, however, to setup CPack to bundle multiple build directories and
  653. construct a package that contains multiple configurations of the same project.
  654. First, we want to ensure that the debug and release builds use different names
  655. for the executables and libraries that will be installed. Let's use `d` as the
  656. postfix for the debug executable and libraries.
  657. Set :variable:`CMAKE_DEBUG_POSTFIX` near the beginning of the top-level
  658. ``CMakeLists.txt`` file:
  659. .. literalinclude:: Complete/CMakeLists.txt
  660. :language: cmake
  661. :start-after: project(Tutorial VERSION 1.0)
  662. :end-before: target_compile_features(tutorial_compiler_flags
  663. And the :prop_tgt:`DEBUG_POSTFIX` property on the tutorial executable:
  664. .. literalinclude:: Complete/CMakeLists.txt
  665. :language: cmake
  666. :start-after: # add the executable
  667. :end-before: # add the binary tree to the search path for include files
  668. Let's also add version numbering to the MathFunctions library. In
  669. ``MathFunctions/CMakeLists.txt``, set the :prop_tgt:`VERSION` and
  670. :prop_tgt:`SOVERSION` properties:
  671. .. literalinclude:: Complete/MathFunctions/CMakeLists.txt
  672. :language: cmake
  673. :start-after: # setup the version numbering
  674. :end-before: # install rules
  675. From the ``Step12`` directory, create ``debug`` and ``release``
  676. subbdirectories. The layout will look like:
  677. .. code-block:: none
  678. - Step12
  679. - debug
  680. - release
  681. Now we need to setup debug and release builds. We can use
  682. :variable:`CMAKE_BUILD_TYPE` to set the configuration type:
  683. .. code-block:: console
  684. cd debug
  685. cmake -DCMAKE_BUILD_TYPE=Debug ..
  686. cmake --build .
  687. cd ../release
  688. cmake -DCMAKE_BUILD_TYPE=Release ..
  689. cmake --build .
  690. Now that both the debug and release builds are complete, we can use a custom
  691. configuration file to package both builds into a single release. In the
  692. ``Step12`` directory, create a file called ``MultiCPackConfig.cmake``. In this
  693. file, first include the default configuration file that was created by the
  694. :manual:`cmake <cmake(1)>` executable.
  695. Next, use the ``CPACK_INSTALL_CMAKE_PROJECTS`` variable to specify which
  696. projects to install. In this case, we want to install both debug and release.
  697. .. literalinclude:: Complete/MultiCPackConfig.cmake
  698. :language: cmake
  699. From the ``Step12`` directory, run :manual:`cpack <cpack(1)>` specifying our
  700. custom configuration file with the ``config`` option:
  701. .. code-block:: console
  702. cpack --config MultiCPackConfig.cmake