The following is a breakdown of the commands inĀ CMakeLists.txt:
- First, we need to define the project and detect the Python interpreter, as follows:
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(recipe-03 LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(PythonInterp QUIET REQUIRED)
- We decided to place the to-be-generated code underĀ ${CMAKE_CURRENT_BINARY_DIR}/generated, and we need to instruct CMake to create this directory:
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/generated)
- The Python script expects an upper bound for the prime numbers, and, with the following command, we can set a default:
set(MAX_NUMBER "100" CACHE STRING "Upper bound for primes")
- Next, we define a custom command to generate the header file:
add_custom_command(
OUTPUT
${CMAKE_CURRENT_BINARY_DIR}/generated/primes.hpp
COMMAND
${PYTHON_EXECUTABLE} generate.py ${MAX_NUMBER} ${CMAKE_CURRENT_BINARY_DIR}/generated/primes.hpp
WORKING_DIRECTORY
${CMAKE_CURRENT_SOURCE_DIR}
DEPENDS
generate.py
)
- Finally, we define the executable and its target, including the directory and dependency:
add_executable(example "")
target_sources(example
PRIVATE
example.cpp
${CMAKE_CURRENT_BINARY_DIR}/generated/primes.hpp
)
target_include_directories(example
PRIVATE
${CMAKE_CURRENT_BINARY_DIR}/generated
)
- We are now ready to test the implementation, as follows:
$ mkdir -p build
$ cd build
$ cmake ..
$ cmake --build .
$ ./example
all prime numbers up to 100: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97