Getting Started with CMake.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805
  1. Step 1: Getting Started with CMake
  2. ==================================
  3. This first step in the CMake tutorial is intended as a quick-start into writing
  4. useful builds for small projects with CMake. By the end, you will be able to
  5. describe executables, libraries, source and header files, and the linkage
  6. relationships between them using CMake.
  7. Each exercise in this step will start with a discussion of the concepts and
  8. commands needed for the exercise. Then, a goal and list of helpful resources are
  9. provided. Each file in the ``Files to Edit`` section is in the ``Step1``
  10. directory and contains one or more ``TODO`` comments. Each ``TODO`` represents
  11. a line or two of code to change or add. The ``TODOs`` are intended to be
  12. completed in numerical order, first complete ``TODO 1`` then ``TODO 2``, etc.
  13. .. note::
  14. Each step in the tutorial builds on the previous, but the steps are not
  15. strictly contiguous. Code not relevant to learning CMake, such as C++
  16. function implementations or CMake code outside the scope of the tutorial,
  17. will sometimes be added between steps.
  18. The ``Getting Started`` section will give some helpful hints and guide you
  19. through the exercise. Then the ``Build and Run`` section will walk step-by-step
  20. through how to build and test the exercise. Finally, at the end of each exercise
  21. the intended solution is reviewed.
  22. Background
  23. ^^^^^^^^^^
  24. Typical usage of CMake revolves around one or more files named
  25. ``CMakeLists.txt``. This file is sometimes referred to as a "lists file" or
  26. "CML". Within a given software project, a ``CMakeLists.txt`` will exist within
  27. any directory where we want to provide instructions to CMake on how to handle
  28. files and operations local to that directory or subdirectories. Each consists of
  29. a set of commands which describe some information or actions relevant to
  30. building the software project.
  31. Not every directory in a software project needs a CML, but it's strongly
  32. recommended that the project root contains one. This will serve as the entry
  33. point for CMake for its initial setup during configuration. This *root* CML
  34. should always contain the same two commands at or near the top the file.
  35. .. code-block:: cmake
  36. cmake_minimum_required(VERSION 3.23)
  37. project(MyProjectName)
  38. The :command:`cmake_minimum_required` is a compatibility guarantee provided by
  39. CMake to the project developer. When called, it ensures that CMake will adopt
  40. the behavior of the listed version. If a later version of CMake is invoked on a
  41. CML containing the above code, it will act exactly as if it were CMake 3.23.
  42. The :command:`project` command is a conceptually simple command which provides a
  43. complex function. It informs CMake that what follows is the description of a
  44. distinct software project of a given name (as opposed to a shell-like script).
  45. When CMake sees the :command:`project` command it performs various checks to
  46. ensure the environment is suitable for building software; such as checking for
  47. compilers and other build tooling, and discovering properties like the
  48. endianness of the host and target machines.
  49. .. note::
  50. While links to complete documentation are provided for every command, it is
  51. not intended the reader understand the full semantics of each CMake command
  52. they use. Effectively learning CMake, like any piece of software, is an
  53. incremental process.
  54. The rest of this tutorial step will be chiefly concerned with the usage of four
  55. more commands. The :command:`add_executable` and :command:`add_library` commands
  56. for describing output artifacts the software project wants to produce, the
  57. :command:`target_sources` command for associating input files with their
  58. respective output artifacts, and the :command:`target_link_libraries` command
  59. for associating output artifacts with one another.
  60. These four commands are the backbone of most CMake usage. As we'll learn, they
  61. are sufficient for describing the majority of a typical project's requirements.
  62. Exercise 1 - Building an Executable
  63. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  64. The most basic CMake project is an executable built from a single source code
  65. file. For simple projects like this, a ``CMakeLists.txt`` file with only
  66. four commands is needed.
  67. .. note::
  68. Although upper, lower and mixed case commands are supported by CMake,
  69. lower case commands are preferred and will be used throughout the tutorial.
  70. The first two commands we have already introduced, :command:`cmake_minimum_required`
  71. and :command:`project`. There is no usage of CMake where the first command in a
  72. root CML will be anything other than :command:`cmake_minimum_required`. There
  73. are some advanced usages where :command:`project` might not be the second
  74. command in a CML, but for our purposes it always will be.
  75. The next command we need is :command:`add_executable`.
  76. This command creates a *target*. In CMake lingo, a target is a name the
  77. developer gives to a collection of properties.
  78. Some examples of properties a target might want to keep track of are:
  79. - The artifact kind (executable, library, header collection, etc)
  80. - Source files
  81. - Include directories
  82. - Output name of an executable or library
  83. - Dependencies
  84. - Compiler and linker flags
  85. The mechanisms of CMake are often best understood as describing and manipulating
  86. targets and their properties. There are many more properties than those listed
  87. here. Documentation of CMake commands will often discuss their function in terms
  88. of the target properties they operate on.
  89. Targets themselves are simply names, a handle to this collection of properties.
  90. Using the :command:`add_executable` command is as easy as specifying the name
  91. we want to use for the target.
  92. .. code-block:: cmake
  93. add_executable(MyProgram)
  94. Now that we have a name for our target, we can start associating properties
  95. with it like source files we want to build and link. The primary command for
  96. this is :command:`target_sources`, which takes as arguments a target name
  97. followed by one or more collections of files.
  98. .. code-block:: cmake
  99. target_sources(MyProgram
  100. PRIVATE
  101. main.cxx
  102. )
  103. .. note::
  104. Paths in CMake are generally either absolute, or relative to the
  105. :variable:`CMAKE_CURRENT_SOURCE_DIR`. We haven't talked about variables like
  106. that yet, so you can read this as "relative to the location of the current
  107. CML".
  108. Each collection of files is prefixed by a :ref:`scope keyword <Target Command Scope>`.
  109. We'll discuss the complete semantics of these keywords when we talk about
  110. linking targets together, but the quick explanation is these describe how a
  111. property should be inherited by dependents of our target.
  112. Typically, nothing depends on an executable. Other programs and libraries don't
  113. need to link to an executable, or inherit headers, or anything of that nature.
  114. So the appropriate scope to use here is ``PRIVATE``, which informs CMake that
  115. this property only belongs to ``MyProgram`` and is not inheritable.
  116. .. note::
  117. This rule is true almost everywhere. Outside advanced and esoteric usages,
  118. the scope keyword for executables should *always* be ``PRIVATE``. The same
  119. holds for implementation files generally, regardless of whether the target
  120. is an executable or a library. The only target which needs to "see" the
  121. ``.cxx`` files is the target building them.
  122. Goal
  123. ----
  124. Understand how to create a simple CMake project with a single executable.
  125. Helpful Resources
  126. -----------------
  127. * :command:`project`
  128. * :command:`cmake_minimum_required`
  129. * :command:`add_executable`
  130. * :command:`target_sources`
  131. Files to Edit
  132. -------------
  133. * ``CMakeLists.txt``
  134. Getting Started
  135. ----------------
  136. The source code for ``Tutorial.cxx`` is provided in the
  137. ``Help/guide/tutorial/Step1/Tutorial`` directory and can be used to compute the
  138. square root of a number. This file does not need to be edited in this exercise.
  139. In the parent directory, ``Help/guide/tutorial/Step1``, is a ``CMakeLists.txt``
  140. file which you will complete. Start with ``TODO 1`` and work through ``TODO 4``.
  141. Build and Run
  142. -------------
  143. Once ``TODO 1`` through ``TODO 4`` have been completed, we are ready to build
  144. and run our project! First, run the :manual:`cmake <cmake(1)>` executable or the
  145. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  146. with your chosen build tool.
  147. For example, from the command line we could navigate to the
  148. ``Help/guide/tutorial/Step1`` directory and invoke CMake for configuration
  149. as follows:
  150. .. code-block:: console
  151. cmake -B build
  152. The :option:`-B <cmake -B>` flag tells CMake to use the given relative
  153. path as the location to generate files and store artifacts during the build
  154. process. If it is omitted, the current working directory is used. It is
  155. generally considered bad practice to do "in-source" builds, placing these
  156. generated files in the source tree itself.
  157. Next, tell CMake to build the project with
  158. :option:`cmake --build <cmake --build>`, passing it the same relative path
  159. we did with the :option:`-B <cmake -B>` flag.
  160. .. code-block:: console
  161. cmake --build build
  162. The ``Tutorial`` executable will be built into the ``build`` directory. For
  163. multi-config generators (e.g. Visual Studio), it might be placed in a
  164. subdirectory such as ``build/Debug``.
  165. Finally, try to use the newly built ``Tutorial``:
  166. .. code-block:: console
  167. Tutorial 4294967296
  168. Tutorial 10
  169. Tutorial
  170. .. note::
  171. Depending on the shell, the correct syntax may be ``Tutorial``,
  172. ``./Tutorial``, ``.\Tutorial``, or even ``.\Tutorial.exe``. For simplicity,
  173. the exercises will use ``Tutorial`` throughout.
  174. Solution
  175. --------
  176. As mentioned above, a four command ``CMakeLists.txt`` is all that we need to get
  177. up and running. The first line should be :command:`cmake_minimum_required`, to
  178. set the CMake version as follows:
  179. .. raw:: html
  180. <details><summary>TODO 1: Click to show/hide answer</summary>
  181. .. literalinclude:: Step3/CMakeLists.txt
  182. :caption: TODO 1: CMakeLists.txt
  183. :name: CMakeLists.txt-cmake_minimum_required
  184. :language: cmake
  185. :start-at: cmake_minimum_required
  186. :end-at: cmake_minimum_required
  187. .. raw:: html
  188. </details>
  189. The next step to make a basic project is to use the :command:`project`
  190. command as follows to set the project name and inform CMake we intend to build
  191. software with this ``CMakeLists.txt``.
  192. .. raw:: html
  193. <details><summary>TODO 2: Click to show/hide answer</summary>
  194. .. literalinclude:: Step3/CMakeLists.txt
  195. :caption: TODO 2: CMakeLists.txt
  196. :name: CMakeLists.txt-project
  197. :language: cmake
  198. :start-at: project
  199. :end-at: project
  200. .. raw:: html
  201. </details>
  202. Now we can setup our executable target for the Tutorial with :command:`add_executable`.
  203. .. raw:: html
  204. <details><summary>TODO 3: Click to show/hide answer</summary>
  205. .. literalinclude:: Step3/Tutorial/CMakeLists.txt
  206. :caption: TODO 3: CMakeLists.txt
  207. :name: CMakeLists.txt-add_executable
  208. :language: cmake
  209. :start-at: add_executable
  210. :end-at: add_executable
  211. .. raw:: html
  212. </details>
  213. Finally, we can associate our source file with the Tutorial executable target
  214. using :command:`target_sources`.
  215. .. raw:: html
  216. <details><summary>TODO 4: Click to show/hide answer</summary>
  217. .. code-block:: cmake
  218. :caption: TODO 4: CMakeLists.txt
  219. :name: CMakeLists.txt-target_sources
  220. target_sources(Tutorial
  221. PRIVATE
  222. Tutorial/Tutorial.cxx
  223. )
  224. .. raw:: html
  225. </details>
  226. Exercise 2 - Building a Library
  227. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  228. We only need to introduce one more command to build a library,
  229. :command:`add_library`. This works exactly like :command:`add_executable`, but
  230. for libraries.
  231. .. code-block:: cmake
  232. add_library(MyLibrary)
  233. However, now is a good time to introduce header files. Header files are not
  234. directly built as translation units, which is to say they are not a *build*
  235. requirement. They are a *usage* requirement. We need to know about header files
  236. in order to build other parts of a given target.
  237. As such, header files are described slightly differently than implementation
  238. files like ``tutorial.cxx``. They're also going to need different
  239. :ref:`scope keywords <Target Command Scope>` than the ``PRIVATE`` keyword we
  240. have used so far.
  241. To describe a collection of header files, we're going to use what's known as a
  242. ``FILE_SET``.
  243. .. code-block:: cmake
  244. target_sources(MyLibrary
  245. PRIVATE
  246. library_implementation.cxx
  247. PUBLIC
  248. FILE_SET myHeaders
  249. TYPE HEADERS
  250. BASE_DIRS
  251. include
  252. FILES
  253. include/library_header.h
  254. )
  255. This is a lot of complexity, but we'll go through it point by point. First,
  256. note that we have our implementation file as a ``PRIVATE`` source, same as
  257. with the executable previously. However, we now use ``PUBLIC`` for our
  258. header file. This allows consumers of our library to "see" the library's
  259. header files.
  260. .. note::
  261. We're not quite ready to discuss the full semantics of scope keywords. We'll
  262. cover them more completely in Exercise 3.
  263. Following the scope keyword is a ``FILE_SET``, a collection of files to be
  264. described as a single unit. A ``FILE_SET`` consists of the following parts:
  265. * ``FILE_SET <name>`` is the name of the ``FILE_SET``. This is a handle which
  266. we can use to describe the collection in other contexts.
  267. * ``TYPE <type>`` is the kind of files we are describing. Most commonly this
  268. will be headers, but newer versions of CMake support other types like C++20
  269. modules.
  270. * ``BASE_DIRS`` is the "base" locations for the files. This can be most easily
  271. understood as the locations that will be described to compilers for header
  272. discovery via ``-I`` flags.
  273. * ``FILES`` is the list of files, same as with the implementation sources list
  274. earlier.
  275. This is a lot of information to describe, so there are some useful shortcuts
  276. we can take. Notably, if the ``FILE_SET`` name is the same as the type, we
  277. don't need to provide the ``TYPE`` field.
  278. .. code-block:: cmake
  279. target_sources(MyLibrary
  280. PRIVATE
  281. library_implementation.cxx
  282. PUBLIC
  283. FILE_SET HEADERS
  284. BASE_DIRS
  285. include
  286. FILES
  287. include/library_header.h
  288. )
  289. There are other shortcuts we can take, but we'll discuss those more in later
  290. steps.
  291. Goal
  292. ----
  293. Build a library.
  294. Helpful Resources
  295. -----------------
  296. * :command:`add_library`
  297. * :command:`target_sources`
  298. Files to Edit
  299. -------------
  300. * ``CMakeLists.txt``
  301. Getting Started
  302. ---------------
  303. Continue editing files in the ``Step1`` directory. Start with ``TODO 5`` and
  304. complete through ``TODO 6``.
  305. Build and Run
  306. -------------
  307. Let's build our project again. Since we already created a build directory and
  308. ran CMake for Exercise 1, we can skip to the build step:
  309. .. code-block:: console
  310. cmake --build build
  311. We should be able to see our library created alongside the Tutorial executable.
  312. Solution
  313. --------
  314. We start by adding the library target in the same manner as the the Tutorial
  315. executable.
  316. .. raw:: html
  317. <details><summary>TODO 5: Click to show/hide answer</summary>
  318. .. literalinclude:: Step3/MathFunctions/CMakeLists.txt
  319. :caption: TODO 5: CMakeLists.txt
  320. :name: CMakeLists.txt-add_library
  321. :language: cmake
  322. :start-at: add_library
  323. :end-at: add_library
  324. .. raw:: html
  325. </details>
  326. Next we need to describe the source files. For the implementation file,
  327. ``MathFunctions.cxx``, this is straight-forward; for the header file
  328. ``MathFunctions.h`` we will need to use a ``FILE_SET``.
  329. We can either give this ``FILE_SET`` its own name, or use the shortcut of naming
  330. it ``HEADERS``. For this tutorial, we'll be using the shortcut, but either
  331. solution is valid.
  332. For ``BASE_DIRS`` we need to determine the directory which will allow for the
  333. desired ``#include <MathFunctions.h>`` directive. To achieve this, the
  334. ``MathFunctions`` folder itself will be a base directory. We would make a
  335. different choice if the desired include directive were
  336. ``#include <MathFunctions/MathFunctions.h>`` or similar.
  337. .. raw:: html
  338. <details><summary>TODO 6: Click to show/hide answer</summary>
  339. .. code-block:: cmake
  340. :caption: TODO 6: CMakeLists.txt
  341. :name: CMakeLists.txt-library_sources
  342. target_sources(MathFunctions
  343. PRIVATE
  344. MathFunctions/MathFunctions.cxx
  345. PUBLIC
  346. FILE_SET HEADERS
  347. BASE_DIRS
  348. MathFunctions
  349. FILES
  350. MathFunctions/MathFunctions.h
  351. )
  352. .. raw:: html
  353. </details>
  354. Exercise 3 - Linking Together Libraries and Executables
  355. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  356. We're ready to combine our library with our executable, for this we must
  357. introduce a new command, :command:`target_link_libraries`. The name of this
  358. command can be somewhat misleading, as it does a great deal more than just
  359. invoke linkers. It describes relationships between targets generally.
  360. .. code-block:: cmake
  361. target_link_libraries(MyProgram
  362. PRIVATE
  363. MyLibrary
  364. )
  365. We're finally ready to discuss the :ref:`scope keywords <Target Command Scope>`.
  366. There are three of them, ``PRIVATE``, ``INTERFACE``, and ``PUBLIC``. These
  367. describe how properties are made available to targets.
  368. * A ``PRIVATE`` property (also called a "non-interface" property) is only
  369. available to the target which owns it, for example ``PRIVATE`` headers will
  370. only be visible to the target they're attached to.
  371. * An ``INTERFACE`` property is only available to targets *which link* the
  372. owning target. The owning target does not have access to these properties. A
  373. header-only library is an example of a collection of ``INTERFACE`` properties,
  374. as header-only libraries do not build anything themselves and do not need to
  375. access their own files.
  376. * ``PUBLIC`` is not a distinct kind of property, but rather is the union of the
  377. ``PRIVATE`` and ``INTERFACE`` properties. Thus requirements described with
  378. ``PUBLIC`` are available to both the owning target and consuming targets.
  379. Consider the following concrete example:
  380. .. code-block:: cmake
  381. target_sources(MyLibrary
  382. PRIVATE
  383. FILE_SET internalOnlyHeaders
  384. TYPE HEADERS
  385. FILES
  386. InternalOnlyHeader.h
  387. INTERFACE
  388. FILE_SET consumerOnlyHeaders
  389. TYPE HEADERS
  390. FILES
  391. ConsumerOnlyHeader.h
  392. PUBLIC
  393. FILE_SET publicHeaders
  394. TYPE HEADERS
  395. FILES
  396. PublicHeader.h
  397. )
  398. .. note::
  399. We excluded ``BASE_DIRS`` for each file set here, that's another shortcut.
  400. When excluded, ``BASE_DIRS`` defaults to the current source directory.
  401. The ``MyLibrary`` target has several properties which will be modified by this
  402. call to :command:`target_sources`. Until now we've used the term "properties"
  403. generically, but properties are themselves named values we can reason about.
  404. Two specific properties which will be modified here are :prop_tgt:`HEADER_SETS`
  405. and :prop_tgt:`INTERFACE_HEADER_SETS`, which both contain lists of header file
  406. sets added via :command:`target_sources`.
  407. The value ``internalOnlyHeaders`` will be added to :prop_tgt:`HEADER_SETS`,
  408. ``consumerOnlyHeaders`` to :prop_tgt:`INTERFACE_HEADER_SETS`, and
  409. ``publicHeaders`` will be added to both.
  410. When a given target is being built, it will use its own *non-interface*
  411. properties (eg, :prop_tgt:`HEADER_SETS`), combined with the *interface*
  412. properties of any targets it links to (eg, :prop_tgt:`INTERFACE_HEADER_SETS`).
  413. .. note::
  414. **It is not necessary to reason about CMake properties at this level of
  415. detail.** The above is described for completeness. Most of the time you don't
  416. need to be concerned with the specific properties a command is modifying.
  417. Scope keywords have a simple intuition associated with them, when considering
  418. a command from the point of view of the target it is being applied to:
  419. **PRIVATE** is for me, **INTERFACE** is for others, **PUBLIC** is for all of
  420. us.
  421. Goal
  422. ----
  423. In the Tutorial executable, use the ``sqrt()`` function provided by the
  424. ``MathFunctions`` library.
  425. Helpful Resources
  426. -----------------
  427. * :command:`target_link_libraries`
  428. Files to Edit
  429. -------------
  430. * ``CMakeLists.txt``
  431. * ``Tutorial/Tutorial.cxx``
  432. Getting Started
  433. ---------------
  434. Continue to edit files from ``Step1``. Start on ``TODO 7`` and complete through
  435. ``TODO 9``. In this exercise, we need to add the ``MathFunctions`` target to
  436. the ``Tutorial`` target's linked libraries using :command:`target_link_libraries`.
  437. After modifying the CML, update ``tutorial.cxx`` to use the
  438. ``mathfunctions::sqrt()`` function instead of ``std::sqrt``.
  439. Build and Run
  440. -------------
  441. Let's build our project again. As before, we already created a build directory
  442. and ran CMake so we can skip to the build step:
  443. .. code-block:: console
  444. cmake --build build
  445. Verify that the output matches what you would expect from the ``MathFunctions``
  446. library.
  447. Solution
  448. --------
  449. In this exercise, we are describing the ``Tutorial`` executable as a consumer
  450. of the ``MathFunctions`` target by adding ``MathFunctions`` to the linked
  451. libraries of the ``Tutorial``.
  452. To achieve this, we modify ``CMakeLists.txt`` file to use the
  453. :command:`target_link_libraries` command, using ``Tutorial`` as the target to
  454. be modified and ``MathFunctions`` as the library we want to add.
  455. .. raw:: html
  456. <details><summary>TODO 7: Click to show/hide answer</summary>
  457. .. literalinclude:: Step3/Tutorial/CMakeLists.txt
  458. :caption: TODO 7: CMakeLists.txt
  459. :name: CMakeLists.txt-target_link_libraries
  460. :language: cmake
  461. :start-at: target_link_libraries(Tutorial
  462. :end-at: )
  463. .. raw:: html
  464. </details>
  465. .. note::
  466. The order here is only loosely relevant. That we call
  467. :command:`target_link_libraries` prior to defining ``MathFunctions`` with
  468. :command:`add_library` doesn't matter to CMake. We are recording that
  469. ``Tutorial`` has a dependency on something named ``MathFunctions``, but what
  470. ``MathFunctions`` means isn't resolved at this stage.
  471. The only target which needs to be defined when calling a CMake command like
  472. :command:`target_sources` or :command:`target_link_libraries` is the target
  473. being modified.
  474. Finally, all that's left to do is modify ``Tutorial.cxx`` to use the newly
  475. provided ``mathfunctions::sqrt`` function. That means adding the appropriate
  476. header file and modifying our ``sqrt()`` call.
  477. .. raw:: html
  478. <details><summary>TODO 8-9: Click to show/hide answer</summary>
  479. .. literalinclude:: Step3/Tutorial/Tutorial.cxx
  480. :caption: TODO 8: Tutorial/Tutorial.cxx
  481. :name: Tutorial/Tutorial.cxx-MathFunctions-headers
  482. :language: c++
  483. :start-at: iostream
  484. :end-at: MathFunctions.h
  485. .. literalinclude:: Step3/Tutorial/Tutorial.cxx
  486. :caption: TODO 9: Tutorial/Tutorial.cxx
  487. :name: Tutorial/Tutorial.cxx-MathFunctions-code
  488. :language: c++
  489. :start-at: calculate square root
  490. :end-at: mathfunctions::sqrt
  491. :dedent: 2
  492. .. raw:: html
  493. </details>
  494. Exercise 4 - Subdirectories
  495. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  496. As we move through the tutorial, we will be adding more commands to manipulate
  497. the ``Tutorial`` executable and the ``MathFunctions`` library. We want to make
  498. sure we keep commands local to the files they are dealing with. While not a
  499. major concern for a small project like this, it can be very useful for large
  500. projects with many targets and thousands of files.
  501. The :command:`add_subdirectory` command allows us to incorporate CMLs located
  502. in subdirectories of the project.
  503. .. code-block:: cmake
  504. add_subdirectory(SubdirectoryName)
  505. When a ``CMakeLists.txt`` in a subdirectory is being processed by CMake all
  506. relative paths described in the subdirectory CML are relative to that
  507. subdirectory, not the top-level CML.
  508. Goal
  509. ----
  510. Use :command:`add_subdirectory` to organize the project.
  511. Helpful Resources
  512. -----------------
  513. * :command:`add_subdirectory`
  514. Files to Edit
  515. -------------
  516. * ``CMakeLists.txt``
  517. * ``Tutorial/CMakeLists.txt``
  518. * ``MathFunctions/CMakeLists.txt``
  519. Getting Started
  520. ---------------
  521. The ``TODOs`` for this step are spread across three ``CMakeLists.txt`` files.
  522. Be sure to pay attention to the path changes necessary when moving the
  523. :command:`target_sources` commands into subdirectories.
  524. .. note::
  525. Previously we said that ``BASE_DIRS`` defaults to the current source
  526. directory. As the desired include directory for ``MathFunctions`` will now be
  527. the same directory as the CML calling :command:`target_sources`, we should
  528. remove the ``BASE_DIRS`` keyword and argument entirely.
  529. Complete ``TODO 10`` through ``TODO 13``.
  530. Build and Run
  531. -------------
  532. Because of the reorganization, we'll need to clean the original build
  533. directory prior to rebuilding (otherwise our new ``Target`` build folder would
  534. conflict with our previously created ``Target`` executable). We can achieve
  535. this with the :option:`--clean-first <cmake--build --clean-first>` flag.
  536. There's no need for a reconfiguration. CMake will automatically
  537. re-configure itself due to the changes in the CMLs.
  538. .. code-block:: console
  539. cmake --build build --clean-first
  540. .. note::
  541. Our executable and library will be output to a new location in the build tree.
  542. A subdirectory which mirrors where :command:`add_executable` and
  543. :command:`add_library` were called in the source tree. You will need to
  544. navigate to this subdirectory in the build tree to run the tutorial
  545. executable in future steps.
  546. You can verify this behavior by deleting the old ``Tutorial`` executable,
  547. and observing that the new one is produced at ``Tutorial/Tutorial``.
  548. Solution
  549. --------
  550. We need to move all the commands concerning the ``Tutorial`` executable into
  551. ``Tutorial/CMakeLists.txt``, and replace them with an
  552. :command:`add_subdirectory` command. We also need to update the path for
  553. ``Tutorial.cxx``.
  554. .. raw:: html
  555. <details><summary>TODO 10-11: Click to show/hide answer</summary>
  556. .. literalinclude:: Step3/Tutorial/CMakeLists.txt
  557. :caption: TODO 10: Tutorial/CMakeLists.txt
  558. :name: Tutorial/CMakeLists.txt-moved
  559. :language: cmake
  560. .. code-block:: cmake
  561. :caption: TODO 11: CMakeLists.txt
  562. :name: CMakeLists.txt-add_subdirectory-Tutorial
  563. add_subdirectory(Tutorial)
  564. .. raw:: html
  565. </details>
  566. We need to do the same with the commands for ``MathFunctions``, changing the
  567. relative paths as appropriate and removing ``BASE_DIRS`` as it is no longer
  568. necessary, the default value will work.
  569. .. raw:: html
  570. <details><summary>TODO 12-13: Click to show/hide answer</summary>
  571. .. literalinclude:: Step3/MathFunctions/CMakeLists.txt
  572. :caption: TODO 12: MathFunctions/CMakeLists.txt
  573. :name: MathFunctions/CMakeLists.txt-moved
  574. :language: cmake
  575. .. literalinclude:: Step3/CMakeLists.txt
  576. :caption: TODO 13: CMakeLists.txt
  577. :name: CMakeLists.txt-add_subdirectory-MathFunctions
  578. :language: cmake
  579. :start-at: add_subdirectory(MathFunctions
  580. :end-at: add_subdirectory(MathFunctions
  581. .. raw:: html
  582. </details>