Modify Config - nenetto/CMakeTemplates GitHub Wiki

One important feature of CMakeTemplates is the Config.h file.

If you open your IDE you will see that your executable or library depends on this file for compilation. This file is CMake-generated, so even if you change it, it will be autogenerated everytime you compile your project.

Since this file is autogenerated, it means that you can modify it depending on some CMake options. For adding defines or global variables you have to go to your project CMake folder. There you will find a Config.h.in file. This file tells CMake how final Config.h will be created. By default, file looks like this:

// This file is created in configuration time
// Variables can be added if we want to add options before compilation
// so compiler can use them.

// Project Variables
#define ${MYPROJECT_NAME}_PROJECT_NAME "${MYPROJECT_NAME}"
#define ${MYPROJECT_NAME}_VERSION_MAJOR ${${MYPROJECT_NAME}_VERSION_MAJOR}
#define ${MYPROJECT_NAME}_VERSION_MINOR ${${MYPROJECT_NAME}_VERSION_MINOR}

// Configuration Variables
#if ${${PROJECT_NAME}_CMAKE_DEBUG}
#define ${MYPROJECT_NAME}_DEBUG_FLAG TRUE
#endif

Where ${MYPROJECT_NAME} will be replaced by your project name.

Now, you could add an option/variable in your project CMakeLists.txt, for example a number of iterations of your algorithm.

option(${PROJECT_NAME}_MY_NUMBER_OF_ITERATIONS "Number of iterations" 200)

With this option, CMake during configuration can modify it as user like. But this is a global variable that will be used during my code, that is why Config.h was created for.

Now, we can add a global variable to Config.h.in

// This file is created in configuration time
// Variables can be added if we want to add options before compilation
// so compiler can use them.

// Project Variables
#define ${MYPROJECT_NAME}_PROJECT_NAME "${MYPROJECT_NAME}"
#define ${MYPROJECT_NAME}_VERSION_MAJOR ${${MYPROJECT_NAME}_VERSION_MAJOR}
#define ${MYPROJECT_NAME}_VERSION_MINOR ${${MYPROJECT_NAME}_VERSION_MINOR}

// Configuration Variables
#if ${${PROJECT_NAME}_CMAKE_DEBUG}
#define ${MYPROJECT_NAME}_DEBUG_FLAG TRUE
#endif

// My Global Variable
#define NumberOfIterations ${PROJECT_NAME}_MY_NUMBER_OF_ITERATIONS

Imagin that your Project is called MyAlgorithm and version is 2.4. The number of iterations was set to 500 during configure in CMake. Now, CMake will generate a Config.h like this

// This file is created in configuration time
// Variables can be added if we want to add options before compilation
// so compiler can use them.

// Project Variables
#define MyAlgorithm_PROJECT_NAME "MyAlgorithm"
#define MyAlgorithm_VERSION_MAJOR 2
#define MyAlgorithm_VERSION_MINOR 4

// Configuration Variables
#if 1
#define MyAlgorithm_DEBUG_FLAG TRUE
#endif

// My Global Variable
#define NumberOfIterations 500