cgcccmakelibm

Can CMake detect if I need to link to libm when using pow in C?


With some compilers, using pow and certain other functions in a C program requires linking to the m library. However, some compilers don't require this and would error out on linking to the m library. An almost identical situation exists for C++ with std::thread and pthread, but the CMake module FindThreads alleviates this entirely - is there some similar module for libm?

What is the best way to detect what to do with CMake? This is my current solution, which is less than ideal because there are many more C compilers than just GCC and MSVC:

if(NOT MSVC)
    target_link_libraries(my-c-target PUBLIC m)
endif()

This works for my purposes but I'm pretty sure there are cases where it would fail and require manual user intervention, which isn't fun for someone who doesn't know about this obscurity. Ideally I don't want the user to have to specify whether their compiler is weird or not via the commandline; I want to detect it automatically within CMake, since this is the entire point of CMake.


Solution

  • You should use the CHECK_FUNCTION_EXISTS command to check if pow can be used without additional flags. If this check fails, you can add m library to CMAKE_REQUIRED_LIBRARIES variable, assuming that linking against libm is what's missing. But you'll need to CHECK_FUNCTION_EXISTS again to make sure the linking is sufficient.

    Sample code:

    include(CheckFunctionExists)
    
    if(NOT POW_FUNCTION_EXISTS AND NOT NEED_LINKING_AGAINST_LIBM)
      CHECK_FUNCTION_EXISTS(pow POW_FUNCTION_EXISTS)
      if(NOT POW_FUNCTION_EXISTS)
          unset(POW_FUNCTION_EXISTS CACHE)
          list(APPEND CMAKE_REQUIRED_LIBRARIES m)
          CHECK_FUNCTION_EXISTS(pow POW_FUNCTION_EXISTS)
          if(POW_FUNCTION_EXISTS)
              set(NEED_LINKING_AGAINST_LIBM True CACHE BOOL "" FORCE)
          else()
              message(FATAL_ERROR "Failed making the pow() function available")
          endif()
      endif()
    endif()
    
    if (NEED_LINKING_AGAINST_LIBM)
         target_link_libraries(your_target_here m)
    endif()