[CMake] Basic question how to find -lm include and lib dir with find_package or otherwise

Chuck Atkins chuck.atkins at kitware.com
Fri Mar 15 12:44:50 EDT 2019


Usually you don't need to use the full path to libm, and it's only needed
sometimes depending on your compiler and toolchain.  I typically use
something like the following to deal with both the implicit and explicit
scenarios:

include(CheckCSourceCompiles)
set(LIBM_TEST_SOURCE "#include<math.h>\nfloat f; int main(){sqrt(f);return
0;}")
check_c_source_compiles("${LIBM_TEST_SOURCE}" HAVE_MATH)
if(HAVE_MATH)
  set(LIBM_LIBRARIES)
else()
  set(CMAKE_REQUIRED_LIBRARIES m)
  check_c_source_compiles("${LIBM_TEST_SOURCE}" HAVE_LIBM_MATH)
  unset(CMAKE_REQUIRED_LIBRARIES)
  if(NOT HAVE_LIBM_MATH)
    message(FATAL_ERROR "Unable to use C math library functions")
  endif()
  set(LIBM_LIBRARIES m)
endif()

target_link_libraries(fooTarget PRIVATE ${LIBM_LIBRARIES})

----------
Chuck Atkins
Staff R&D Engineer, Scientific Computing
Kitware, Inc.



On Fri, Mar 15, 2019 at 7:46 AM frodak17 <frodak17 at gmail.com> wrote:

>
>
> On Thu, Mar 14, 2019 at 8:53 PM Workbench at gmx.at <workbench at gmx.at> wrote:
>
>> Hi everyone,
>>
>> i'm searching for a way to find the right include dir so that -lm can be
>> found, the is not find_package for this, is /usr/lib and /usr/include a
>> default because he find it without me adding any include or lib path for
>> the build.
>>
>>
>>
> It seems strange that you need to do this.  In my experience 'm' is just
> the math portion of the 'c' library.  Depending on which host and toolset
> you are using there can be multiple version of the 'm' library depending on
> target architecture and other options used.  The linker should just use the
> correct 'm' library just as it uses the correct 'c' library.  It could be
> in /usr/lib depending on how the compiler was packaged for your host.
> --
>
> Powered by www.kitware.com
>
> Please keep messages on-topic and check the CMake FAQ at:
> http://www.cmake.org/Wiki/CMake_FAQ
>
> Kitware offers various services to support the CMake community. For more
> information on each offering, please visit:
>
> CMake Support: http://cmake.org/cmake/help/support.html
> CMake Consulting: http://cmake.org/cmake/help/consulting.html
> CMake Training Courses: http://cmake.org/cmake/help/training.html
>
> Visit other Kitware open-source projects at
> http://www.kitware.com/opensource/opensource.html
>
> Follow this link to subscribe/unsubscribe:
> https://cmake.org/mailman/listinfo/cmake
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://cmake.org/pipermail/cmake/attachments/20190315/8ef5c2a4/attachment.html>


More information about the CMake mailing list