Adding Usage Requirements for a Library.rst 1.8 KB

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