Adding System Introspection.rst 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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
  13. ``m`` library and try again.
  14. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  15. :caption: MathFunctions/CMakeLists.txt
  16. :language: cmake
  17. :start-after: # does this system provide the log and exp functions?
  18. :end-before: # add compile definitions
  19. If available, use :command:`target_compile_definitions` to specify
  20. ``HAVE_LOG`` and ``HAVE_EXP`` as ``PRIVATE`` compile definitions.
  21. .. literalinclude:: Step6/MathFunctions/CMakeLists.txt
  22. :caption: MathFunctions/CMakeLists.txt
  23. :language: cmake
  24. :start-after: # add compile definitions
  25. :end-before: # install rules
  26. If ``log`` and ``exp`` are available on the system, then we will use them to
  27. compute the square root in the ``mysqrt`` function. Add the following code to
  28. the ``mysqrt`` function in ``MathFunctions/mysqrt.cxx`` (don't forget the
  29. ``#endif`` before returning the result!):
  30. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  31. :caption: MathFunctions/mysqrt.cxx
  32. :language: c++
  33. :start-after: // if we have both log and exp then use them
  34. :end-before: // do ten iterations
  35. We will also need to modify ``mysqrt.cxx`` to include ``cmath``.
  36. .. literalinclude:: Step6/MathFunctions/mysqrt.cxx
  37. :caption: MathFunctions/mysqrt.cxx
  38. :language: c++
  39. :end-before: #include <iostream>
  40. Run the :manual:`cmake <cmake(1)>` executable or the
  41. :manual:`cmake-gui <cmake-gui(1)>` to configure the project and then build it
  42. with your chosen build tool and run the Tutorial executable.
  43. Which function gives better results now, ``sqrt`` or ``mysqrt``?