How to test if CMake found a library with find_library

Simply do

if(MY_LIB)
    #found
    ...
else()
    #not found
    ...
endif()

You can simply test the variable as such, e.g.:

find_library(LUA_LIB lua)
if(NOT LUA_LIB)
  message(FATAL_ERROR "lua library not found")
endif()

Example output:

CMake Error at CMakeLists.txt:99 (message):
  lua library not found


-- Configuring incomplete, errors occurred!

Note that we use

if(NOT LUA_LIB)

and not

if(NOT ${LUA_LIB})

because of the different semantics.

With ${}, the variable LUA_LIB is substitued before if() is evaluated. As part of the evaluation the content would then be interpreted as variable name, unless it matches the definition of a constant. And this isn't what we want.

Tags:

Cmake