1 Step 3: Adding Usage Requirements for a Library
2 ===============================================
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
9 - :command:`target_compile_definitions`
10 - :command:`target_compile_options`
11 - :command:`target_include_directories`
12 - :command:`target_link_libraries`
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``
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``:
24 .. literalinclude:: Step4/MathFunctions/CMakeLists.txt
25 :caption: MathFunctions/CMakeLists.txt
26 :name: MathFunctions/CMakeLists.txt-target_include_directories-INTERFACE
28 :start-after: # to find MathFunctions.h
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:
34 .. literalinclude:: Step4/CMakeLists.txt
35 :caption: CMakeLists.txt
36 :name: CMakeLists.txt-remove-EXTRA_INCLUDES
38 :start-after: # add the MathFunctions library
39 :end-before: # add the executable
43 .. literalinclude:: Step4/CMakeLists.txt
44 :caption: CMakeLists.txt
45 :name: CMakeLists.txt-target_include_directories-remove-EXTRA_INCLUDES
47 :start-after: # so that we will find TutorialConfig.h
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