Force find_library to search again

cmake

Solution

One solution I can come with after some testing is manually setting the variable `MYLIBRARY_LIBRARY` to `MYLIBRARY_LIBRARY-NOTFOUND` before calling `find_library`.

If you want to actually execute `find_library` only if the circumstances have changed since last configure (in this case only if the user changed `CUDA_BACKEND`), you can recorder the last state of your settings and check whether they changed. The next code is not tested, but should work:

# Where CUDA_BACKEND is set
set (CUDA_BACKEND "OFF" CACHE STRING "Whether to use CUDA")
if ("${CUDA_BACKEND}" STREQ "${CUDA_BACKEND_LAST}")
    set (CUDA_BACKEND_CHANGED "OFF")
else ("${CUDA_BACKEND}" STREQ "${CUDA_BACKEND_LAST}")
    set (CUDA_BACKEND_CHANGED "ON")
endif ("${CUDA_BACKEND}" STREQ "${CUDA_BACKEND_LAST}")
set (CUDA_BACKEND_LAST "${CUDA_BACKEND}")

# Later on, where you define the name of the library
if ( CUDA_BACKEND )
    set ( MYLIBRARY_NAME "MyLibraryCUDA" )
else ( CUDA_BACKEND )
    set ( MYLIBRARY_NAME "MyLibrary" )
endif ( CUDA_BACKEND )

if (CUDA_BACKEND_CHANGED)
    set (MYLIBRARY_LIBRARY "MYLIBRARY_LIBRARY-NOTFOUND")
endif (CUDA_BACKEND_CHANGED)

find_library ( MYLIBRARY_LIBRARY
    NAMES "${MYLIBRARY_NAME}"
    PATHS "${MYLIBRARY_ABSOLUTE_PATH}/lib"
)

Problem

In my CMake script I have have to link against a library which can have two different names, depending on a cache variable. The library can be libMyLibrary.a or libMyLibraryCUDA.a, depending on whether `CUDA_BACKEND` is set to ON or OFF. `CUDA_BACKEND` is a cache variable. Both libraries are in the same directory, whose path is stored (after user's input) in the variable `MYLIBRARY_ABSOLUTE_PATH`. ``` if ( CUDA_BACKEND ) set ( MYLIBRARY_NAME "MyLibraryCUDA" ) else ( CUDA_BACKEND ) set ( MYLIBRARY_NAME "MyLibrary" ) endif ( CUDA_BACKEND ) find_library ( MYLIBRARY_LIBRARY NAMES "${MYLIBRARY_NAME}" PATHS "${MYLIBRARY_ABSOLUTE_PATH}/lib" ) ``` If the user changes the value of `CUDA_BACKEND` and runs cmake, `find_library` is not run again, since the variable `MYLIBRARY_LIBRARY` contains a valid path (following the documentation): Once one of the calls succeeds the result variable will be set and stored in the cache so that no call will search again. So, my question is: what is the cleanest way of forcing `find_library` to search again the library is the value of `CUDA_BACKEND` changes?

Original source