Adding System Introspection.rst 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. Step 5: Adding System Introspection
  2. ===================================
  3. Let us consider adding some code to our project that depends on features the
  4. target platform may not have. For this example, we will add some code that
  5. depends on whether or not the target platform has the ``log`` and ``exp``
  6. functions. Of course almost every platform has these functions but for this
  7. tutorial assume that they are not common.
  8. If the platform has ``log`` and ``exp`` then we will use them to compute the
  9. square root in the ``mysqrt`` function. We first test for the availability of
  10. these functions using the :module:`CheckCXXSourceCompiles` module in
  11. ``MathFunctions/CMakeLists.txt``.
  12. Add the checks for ``log`` and ``exp`` to ``MathFunctions/CMakeLists.txt``,
  13. after the call to :command:`target_include_directories`:
  14. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  15. :caption: MathFunctions/CMakeLists.txt
  16. :name: MathFunctions/CMakeLists.txt-check_cxx_source_compiles
  17. :language: cmake
  18. :start-after: # to find MathFunctions.h, while we don't.
  19. :end-before: # add compile definitions
  20. If available, use :command:`target_compile_definitions` to specify
  21. ``HAVE_LOG`` and ``HAVE_EXP`` as ``PRIVATE`` compile definitions.
  22. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  23. :caption: MathFunctions/CMakeLists.txt
  24. :name: MathFunctions/CMakeLists.txt-target_compile_definitions
  25. :language: cmake
  26. :start-after: # add compile definitions
  27. :end-before: # install rules
  28. If ``log`` and ``exp`` are available on the system, then we will use them to
  29. compute the square root in the ``mysqrt`` function. Add the following code to
  30. the ``mysqrt`` function in ``MathFunctions/mysqrt.cxx`` (don't forget the
  31. ``#endif`` before returning the result!):
  32. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  33. :caption: MathFunctions/mysqrt.cxx
  34. :name: MathFunctions/mysqrt.cxx-ifdef
  35. :language: c++
  36. :start-after: // if we have both log and exp then use them
  37. :end-before: // do ten iterations
  38. We will also need to modify ``mysqrt.cxx`` to include ``cmath``.
  39. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  40. :caption: MathFunctions/mysqrt.cxx
  41. :name: MathFunctions/mysqrt.cxx-include-cmath
  42. :language: c++
  43. :end-before: #include <iostream>
  44. Run the :manual:`cmake <cmake(1)>` executable or the
  45. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  46. with your chosen build tool and run the Tutorial executable.
  47. Which function gives better results now, ``sqrt`` or ``mysqrt``?