Search code examples
c++cmakelibrariesbuild-type

find_library for different build types


Some close source CMake-based project contains the following line in CMakeLists.txt (libname is just a placeholder here):

find_library(LIBNAME_LIB NAMES Libname_d Libname)

Libname_d is used for debug builds, Libname for release. But it only works correctly if we have installed only one version and that version corresponds cmake build type.

In case if we have both versions installed (Libname_d and Libname) and the current CMAKE_BUILD_TYPE = Release we found only Libname_d.

How to properly handle different library build types in find_library call? Maybe we should use something else?


Solution

  • Use different calls to find_library for every configuration of the library:

    find_library(LIBNAME_LIB Libname)
    find_library(LIBNAME_LIB_DEBUG Libname_d)
    

    That way you will get two variables, each of which points to the specific configuration of a library.

    Having those variable you could construct an IMPORTED target with two library locations: one for a release build, and one for debug:

    add_library(LIBNAME IMPORTED)
    set_target_properties(LIBNAME PROPERTIES
      IMPORTED_LOCATION_RELEASE ${LIBNAME_LIB}
      IMPORTED_LOCATION_DEBUG ${LIBNAME_LIB_DEBUG}
    )
    

    When a consumer project will link with that target, CMake will automatically choose the location suitable for the configuration:

    target_link_libraries(my_exe PRIVATE LIBNAME)
    

    When pass to find_library several names, you ask CMake to find a single file which name corresponds to either of those names.