FindStandardMathLibrary.cmake 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # - Try to find how to link to the standard math library, if anything at all is needed to do.
  2. # On most platforms this is automatic, but for example it's not automatic on QNX.
  3. #
  4. # Once done this will define
  5. #
  6. # STANDARD_MATH_LIBRARY_FOUND - we found how to successfully link to the standard math library
  7. # STANDARD_MATH_LIBRARY - the name of the standard library that one has to link to.
  8. # -- this will be left empty if it's automatic (most platforms).
  9. # -- this will be set to "m" on platforms where one must explicitly
  10. # pass the "-lm" linker flag.
  11. #
  12. # Copyright (c) 2010 Benoit Jacob <jacob.benoit.1@gmail.com>
  13. # 2020 Susi Lehtola <susi.lehtola@gmail.com>
  14. # Redistribution and use is allowed according to the terms of the 2-clause BSD license.
  15. include(CheckCXXSourceCompiles)
  16. # a little test program for c++ math functions.
  17. # notice the std:: is required on some platforms such as QNX
  18. # notice the (void) is required if -Wall (-Wunused-value) is added to CMAKE_CXX_FLAG
  19. # We read in the arguments from standard input to avoid the compiler optimizing away the calls
  20. set(find_standard_math_library_test_program
  21. "
  22. #include<cmath>
  23. int main(int argc, char **){
  24. return int(std::sin(double(argc)) + std::log(double(argc)));
  25. }")
  26. # first try compiling/linking the test program without any linker flags
  27. set(CMAKE_REQUIRED_FLAGS "")
  28. set(CMAKE_REQUIRED_LIBRARIES "")
  29. CHECK_CXX_SOURCE_COMPILES(
  30. "${find_standard_math_library_test_program}"
  31. standard_math_library_linked_to_automatically
  32. )
  33. if(standard_math_library_linked_to_automatically)
  34. # the test program linked successfully without any linker flag.
  35. set(STANDARD_MATH_LIBRARY "")
  36. set(STANDARD_MATH_LIBRARY_FOUND TRUE)
  37. else()
  38. # the test program did not link successfully without any linker flag.
  39. # This is a very uncommon case that so far we only saw on QNX. The next try is the
  40. # standard name 'm' for the standard math library.
  41. set(CMAKE_REQUIRED_LIBRARIES "m")
  42. CHECK_CXX_SOURCE_COMPILES(
  43. "${find_standard_math_library_test_program}"
  44. standard_math_library_linked_to_as_m)
  45. if(standard_math_library_linked_to_as_m)
  46. # the test program linked successfully when linking to the 'm' library
  47. set(STANDARD_MATH_LIBRARY "m")
  48. set(STANDARD_MATH_LIBRARY_FOUND TRUE)
  49. else()
  50. # the test program still doesn't link successfully
  51. set(STANDARD_MATH_LIBRARY_FOUND FALSE)
  52. endif()
  53. endif()