index.rst 37 KB

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