This is a step-by-step breakdown of our three CMake files:
- In this recipe, we will not compile any code and our language requirement is therefore NONE:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(recipe-05 LANGUAGES NONE)
- We then define an include_guard macro, which we place in a separate module:
# (re)defines include_guard
include(cmake/include_guard.cmake)
- The cmake/include_guard.cmake file contains the following (we will discuss it in detail shortly):
macro(include_guard)
if (CMAKE_VERSION VERSION_LESS "3.10")
# for CMake below 3.10 we define our
# own include_guard(GLOBAL)
message(STATUS "calling our custom include_guard")
# if this macro is called the first time
# we start with an empty list
if(NOT DEFINED included_modules)
set(included_modules)
endif()
if ("${CMAKE_CURRENT_LIST_FILE}" IN_LIST included_modules)
message(WARNING "module ${CMAKE_CURRENT_LIST_FILE} processed more than once")
endif()
list(APPEND included_modules ${CMAKE_CURRENT_LIST_FILE})
else()
# for CMake 3.10 or higher we augment
# the built-in include_guard
message(STATUS "calling the built-in include_guard")
_include_guard(${ARGV})
endif()
endmacro()
- In the main CMakeLists.txt, we then simulate including the custom module accidentally twice:
include(cmake/custom.cmake)
include(cmake/custom.cmake)
- Finally, we configure with the following commands:
$ mkdir -p build
$ cd build
$ cmake ..
- The result using CMake 3.10 and higher is as follows:
-- calling the built-in include_guard
-- custom.cmake is included and processed
-- calling the built-in include_guard
- The result using CMake below 3.10 is as follows:
-- calling our custom include_guard
-- custom.cmake is included and processed
-- calling our custom include_guard
CMake Warning at cmake/include_guard.cmake:7 (message):
module
/home/user/example/cmake/custom.cmake
processed more than once
Call Stack (most recent call first):
cmake/custom.cmake:1 (include_guard)
CMakeLists.txt:12 (include)