cmake Search and use installed packages, libraries and programs Use find_package and Find.cmake modules


Example

The default way to find installed packages with CMake is the use the find_package function in conjunction with a Find<package>.cmake file. The purpose of the file is to define the search rules for the package and set different variables, such as <package>_FOUND, <package>_INCLUDE_DIRS and <package>_LIBRARIES.

Many Find<package>.cmake file are already defined by default in CMake. However, if there is no file for the package you need, you can always write your own and put it inside ${CMAKE_SOURCE_DIR}/cmake/modules (or any other directory if CMAKE_MODULE_PATH was overridden)

A list of default modules can be found in the manual (v3.6). It is essential to check the manual according to the version of CMake used in the project or else there could be missing modules. It is also possible to find the installed modules with cmake --help-module-list.

There is a nice example for a FindSDL2.cmake on Github

Here's a basic CMakeLists.txt that would require SDL2:

cmake_minimum_required(2.8 FATAL_ERROR)
project("SDL2Test")

set(CMAKE_MODULE_PATH "${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}/cmake/modules")
find_package(SDL2 REQUIRED)

include_directories(${SDL2_INCLUDE_DIRS})
add_executable(${PROJECT_NAME} main.c)
target_link_libraries(${PROJECT_NAME} ${SDL2_LIBRARIES})