“Configured” Header Files

Problem

  • Want to output project version in executables

  • ⟶ Set version using PROJECT()

  • Output using MESSAGE()

    PROJECT(Demo VERSION 42.666)
    MESSAGE(DEBUG "Major: ${Demo_VERSION_MAJOR}")
    MESSAGE(DEBUG "Major: ${Demo_VERSION_MINOR}")
    
  • Question: how to make those available to compiled code?

  • Answer: CONFIGURE_FILE()

Configured Files

  • Header file template that contains CMake variable substitutions

    // This file is generated, do not modify
    
    #define DEMO_MAJOR @Demo_VERSION_MAJOR@
    #define DEMO_MINOR @Demo_VERSION_MINOR@
    
  • Let CMake perform substitutions

    CONFIGURE_FILE(DemoConfig.h.in DemoConfig.h)
    
  • Converted to ${CMAKE_CURRENT_BINARY_DIR}/DemoConfig.h

Use In Compiled Code

  • Pick up CMake variables from configure file (code/bin/hello-first.cpp and code/bin/hello-second.cpp)

    #include <DemoConfig.h>
    // ...
    std::cout << "Version " << DEMO_MAJOR << '.' << DEMO_MINOR << std::endl;
    
  • Does not compile ⟶ include path missing

    bin/hello-first.cpp:4:10: fatal error: DemoConfig.h: No such file or directory
        4 | #include <DemoConfig.h>
          |          ^~~~~~~~~~~~~~
    
  • Solution: set include path for all (to add a dependency would be overkill but could be done)

    Toplevel CMakeLists.txt
    INCLUDE_DIRECTORIES(${CMAKE_CURRENT_BINARY_DIR})