Adding Usage Requirements for a Library.rst 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. :name: MathFunctions/CMakeLists.txt-target_include_directories-INTERFACE
  22. :language: cmake
  23. :start-after: # to find MathFunctions.h
  24. Now that we've specified usage requirements for ``MathFunctions`` we can safely
  25. remove our uses of the ``EXTRA_INCLUDES`` variable from the top-level
  26. ``CMakeLists.txt``, here:
  27. .. literalinclude:: Step4/CMakeLists.txt
  28. :caption: CMakeLists.txt
  29. :name: CMakeLists.txt-remove-EXTRA_INCLUDES
  30. :language: cmake
  31. :start-after: # add the MathFunctions library
  32. :end-before: # add the executable
  33. And here:
  34. .. literalinclude:: Step4/CMakeLists.txt
  35. :caption: CMakeLists.txt
  36. :name: CMakeLists.txt-target_include_directories-remove-EXTRA_INCLUDES
  37. :language: cmake
  38. :start-after: # so that we will find TutorialConfig.h
  39. Once this is done, run the :manual:`cmake <cmake(1)>` executable or the
  40. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  41. with your chosen build tool or by using ``cmake --build .`` from the build
  42. directory.