Adding System Introspection.rst 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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:`CheckSymbolExists` module in
  11. ``MathFunctions/CMakeLists.txt``. On some platforms, we will need to link to
  12. the m library. If ``log`` and ``exp`` are not initially found, require the m
  13. library and try again.
  14. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  15. :language: cmake
  16. :start-after: # does this system provide the log and exp functions?
  17. :end-before: # add compile definitions
  18. If available, use :command:`target_compile_definitions` to specify
  19. ``HAVE_LOG`` and ``HAVE_EXP`` as ``PRIVATE`` compile definitions.
  20. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  21. :language: cmake
  22. :start-after: # add compile definitions
  23. :end-before: # install rules
  24. If ``log`` and ``exp`` are available on the system, then we will use them to
  25. compute the square root in the ``mysqrt`` function. Add the following code to
  26. the ``mysqrt`` function in ``MathFunctions/mysqrt.cxx`` (don't forget the
  27. ``#endif`` before returning the result!):
  28. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  29. :language: c++
  30. :start-after: // if we have both log and exp then use them
  31. :end-before: // do ten iterations
  32. We will also need to modify ``mysqrt.cxx`` to include ``cmath``.
  33. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  34. :language: c++
  35. :end-before: #include <iostream>
  36. 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 and run the Tutorial executable.
  39. Which function gives better results now, sqrt or mysqrt?