How to do it

The following illustrates the steps to record versioning information from Git:

  1. In CMakeLists.txt, we first define the project and language support:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)project(recipe-06 LANGUAGES CXX)set(CMAKE_CXX_STANDARD 11)set(CMAKE_CXX_EXTENSIONS OFF)set(CMAKE_CXX_STANDARD_REQUIRED ON)
  1. We then use the following code snippet to define a variable, GIT_HASH:
# in case Git is not available, we default to "unknown"set(GIT_HASH "unknown")# find Git and if available set GIT_HASH variablefind_package(Git QUIET)if(GIT_FOUND)  execute_process(    COMMAND ${GIT_EXECUTABLE} log -1 --pretty=format:%h    OUTPUT_VARIABLE GIT_HASH    OUTPUT_STRIP_TRAILING_WHITESPACE    ERROR_QUIET    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ...

Get CMake Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.