We wish to check whether the UUID system library on GNU/Linux can be linked against, before embarking on building our own C++ project. This can be achieved with the following series of steps:
- We start by declaring a mixed C and C++11 program. This is needed since the test code snippet we want to compile and run is in the C language:
cmake_minimum_required(VERSION 3.6 FATAL_ERROR)
project(recipe-08 LANGUAGES CXX C)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
- We need to find the UUID library on our system. This is achieved by using pkg-config. We ask for the search to return a CMake imported target using the IMPORTED_TARGET argument:
find_package(PkgConfig REQUIRED QUIET)
pkg_search_module(UUID REQUIRED uuid IMPORTED_TARGET)
if(TARGET PkgConfig::UUID)
message(STATUS "Found libuuid")
endif()
- Next, we include the CheckCSourceRuns.cmake module. There is a similar CheckCXXSourceRuns.cmake module for C++. No such module is available for the Fortran language as of CMake 3.11, however:
include(CheckCSourceRuns)
- We declare an _test_uuid variable containing the C code snippet to compile and run:
set(_test_uuid
"
#include <uuid/uuid.h>
int main(int argc, char * argv[]) {
uuid_t uuid;
uuid_generate(uuid);
return 0;
}
")
- We declare the CMAKE_REQUIRED_LIBRARIES variable to fine-tune the call to the check_c_source_runs function. Next, we issue a call to check_c_source_runs with the test snippet as the first argument and the _runs variable as the second argument, to hold the result of the check performed. We also unset the CMAKE_REQUIRED_LIBRARIES variable:
set(CMAKE_REQUIRED_LIBRARIES PkgConfig::UUID)
check_c_source_runs("${_test_uuid}" _runs)
unset(CMAKE_REQUIRED_LIBRARIES)
- If the check did not succeed, either because the snippet didn't compile or because it didn't run, we stop the configuration with a fatal error:
if(NOT _runs)
message(FATAL_ERROR "Cannot run a simple C executable using libuuid!")
endif()
- Otherwise, we move on and add the C++ executable as a target and link against UUID:
add_executable(use-uuid use-uuid.cpp)
target_link_libraries(use-uuid
PUBLIC
PkgConfig::UUID
)