Adding Usage Requirements for a Library.rst 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 `Adding a Library (Step 2)`_ to use the modern
  12. CMake approach of usage requirements. We first state that anybody linking to
  13. MathFunctions needs to include the current source directory, while
  14. MathFunctions itself doesn't. So this can become an ``INTERFACE`` usage
  15. 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. :language: cmake
  21. :start-after: # to find MathFunctions.h
  22. Now that we've specified usage requirements for MathFunctions we can safely
  23. remove our uses of the ``EXTRA_INCLUDES`` variable from the top-level
  24. ``CMakeLists.txt``, here:
  25. .. literalinclude:: Step4/CMakeLists.txt
  26. :language: cmake
  27. :start-after: # add the MathFunctions library
  28. :end-before: # add the executable
  29. And here:
  30. .. literalinclude:: Step4/CMakeLists.txt
  31. :language: cmake
  32. :start-after: # so that we will find TutorialConfig.h
  33. Once this is done, run the :manual:`cmake <cmake(1)>` executable or the
  34. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  35. with your chosen build tool or by using ``cmake --build .`` from the build
  36. directory.