How it works

To generate the header file, we defined a custom command that executes the generate.py script and takes ${MAX_NUMBER} and the file path (${CMAKE_CURRENT_BINARY_DIR}/generated/primes.hpp) as arguments:

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  )

In order to trigger the source code generation, we need to add it as a source code dependency in the definition of the executable, a task easily achieved with target_sources:

target_sources(example  PRIVATE    example.cpp    ${CMAKE_CURRENT_BINARY_DIR}/generated/primes.hpp  )

In the preceding ...

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.