a8e914edaf86b4efc9c5efea9d6ee4950b4cf32a
[platform/upstream/cmake.git] / Help / guide / tutorial / Adding Usage Requirements for a Library.rst
1 Step 3: Adding Usage Requirements for a Library
2 ===============================================
3
4 Usage requirements allow for far better control over a library or executable's
5 link and include line while also giving more control over the transitive
6 property of targets inside CMake. The primary commands that leverage usage
7 requirements are:
8
9   - :command:`target_compile_definitions`
10   - :command:`target_compile_options`
11   - :command:`target_include_directories`
12   - :command:`target_link_libraries`
13
14 Let's refactor our code from :guide:`tutorial/Adding a Library` to use the
15 modern CMake approach of usage requirements. We first state that anybody
16 linking to ``MathFunctions`` needs to include the current source directory,
17 while ``MathFunctions`` itself doesn't. So this can become an ``INTERFACE``
18 usage requirement.
19
20 Remember ``INTERFACE`` means things that consumers require but the producer
21 doesn't. Add the following lines to the end of
22 ``MathFunctions/CMakeLists.txt``:
23
24 .. literalinclude:: Step4/MathFunctions/CMakeLists.txt
25   :caption: MathFunctions/CMakeLists.txt
26   :name: MathFunctions/CMakeLists.txt-target_include_directories-INTERFACE
27   :language: cmake
28   :start-after: # to find MathFunctions.h
29
30 Now that we've specified usage requirements for ``MathFunctions`` we can safely
31 remove our uses of the ``EXTRA_INCLUDES`` variable from the top-level
32 ``CMakeLists.txt``, here:
33
34 .. literalinclude:: Step4/CMakeLists.txt
35   :caption: CMakeLists.txt
36   :name: CMakeLists.txt-remove-EXTRA_INCLUDES
37   :language: cmake
38   :start-after: # add the MathFunctions library
39   :end-before: # add the executable
40
41 And here:
42
43 .. literalinclude:: Step4/CMakeLists.txt
44   :caption: CMakeLists.txt
45   :name: CMakeLists.txt-target_include_directories-remove-EXTRA_INCLUDES
46   :language: cmake
47   :start-after: # so that we will find TutorialConfig.h
48
49 Once this is done, run the :manual:`cmake  <cmake(1)>` executable or the
50 :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
51 with your chosen build tool or by using ``cmake --build .`` from the build
52 directory.