CMake/Configuration files

A configuration file is used in the code either to enable/disable features, portability and/or setting flags. The configuration file is usually a header file which is included in every source file (which needs it at least). However, I don't think the CMake manual is as straightforward as it should be.

The first thing to do is to create a template for the configuration file. I will call this file but anything will do, as long as it doesn't conflict with any other file and it must not be the same as the created file. The template file is processed by CMake which works almost like a simple c/c++ preprocessor. By using #cmakedefine you can put defines in the output. For instance, by putting "#cmakedefine FOO" CMake will replace that line with either "#define FOO" or "/* #define FOO */" depending on the state of the corresponding variable ${FOO} in CMake. To get the value of the variable you can use @FOO@, like "#cmakedefine FOO @FOO@".

Secondly in your use CONFIGURE_FILE to set the filenames. The first argument is the template and the second is the file that will be created. Again, make sure that these aren't the same! To get options for enabling or disabling components you can use the OPTION macro.

Sample files:

 OPTION( WITH_FOO "Enable FOO support" ON ) OPTION( WITH_BAR "Enable BAR component" OFF ) SET( BAZ 18 ) CONFIGURE_FILE( ${CMAKE_SOURCE_DIR}/include/config.h.cmake ${CMAKE_SOURCE_DIR}/include/config.h )
 * 1) OPTION( VARIABLE "Description" Initial state)


 * 1) ifndef CONFIG_H
 * 2) define CONFIG_H


 * 1) cmakedefine WITH_FOO
 * 2) cmakedefine WITH_BAR


 * 1) cmakedefine BAZ @BAZ@


 * 1) endif // CONFIG_H

Output: 
 * 1) ifndef CONFIG_H
 * 2) define CONFIG_H

/* #define WITH_BAR */
 * 1) define WITH_FOO


 * 1) define BAZ 18


 * 1) endif // CONFIG_H