glades
glades

Reputation: 4737

Predeclare search location for anticipated find_library()-call

I want to include an external library as a subproject into my own project and link its target(s) statically against my own lib.

The said project somewhere in its CMake calls the following find-functions:

find_library(MBEDTLS_LIBRARY mbedtls)
find_library(MBEDX509_LIBRARY mbedx509)
find_library(MBEDCRYPTO_LIBRARY mbedcrypto)

The subproject expects mbedtls to already be installed somewhere on the system, but it didn't consider the fact that I want to link statically. My approach is to now FetchContent mbedtls and provide the find_library() calls with the prebuilt static libraries.

Now I need a way provide those find_library-calls with the right search directory, of course without modifying its source code. Can I somehow set a prefix path? I know I could probably set CMAKE_PREFIX_PATH but that seems like an ugly hack and it would probably affect other find_library()-calls within the project which also exist. Is there a more "constrained" way?

Upvotes: 0

Views: 37

Answers (1)

Tsyvarev
Tsyvarev

Reputation: 65870

Can I somehow set a prefix path?

Setting a prefix path won't help find_library to locate the library, because command find_library searches the file at configuration stage, but the library is built only on build stage.

Instead, you may write the target name to the CACHE variable, which is passed to find_library as the first argument:

  • When find the result variable to be already set, find_library won't search the library file.
  • In most cases a project uses result of find_library in the call to target_link_libraries, so having the library target in the result variable will fit to the project's expectations.

Example:

FetchContent_Declare(mbedtls ...)
FetchContent_MakeAvailable(mbedtls)

set(MBEDTLS_LIBRARY MbedTLS::mbedtls CACHE INTERNAL "mbedtls library target")

With such setup the following

find_library(MBEDTLS_LIBRARY mbedtls)

will do nothing, since the variable MBEDTLS_LIBRARY is already set.

And if the project will use this variable like

target_link_libraries(<executable> ${MBEDTLS_LIBRARY})

then it effectively gets

target_link_libraries(<executable> MbedTLS::mbedtls)

Name of the target which should be assigned to the variable could sometime be found from the project's documentation, but otherwise you need to look into the project's sources (CMakeLists.txt).

E.g. in case of mbedtls project, the library target mbedtls is created with add_library() call, and MbedTLS::mbedtls is created as ALIAS for it.

Upvotes: 1

Related Questions