CMake/Configuration files

From Sidvind
Jump to: navigation, search

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 config.h.cmake 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 CMakeLists.txt 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:

Code: CMakeLists.txt (view, download)

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

Code: include/config.h.cmake (view, download)

  1. #ifndef CONFIG_H
  2. #define CONFIG_H
  3.  
  4. #cmakedefine WITH_FOO
  5. #cmakedefine WITH_BAR
  6.  
  7. #cmakedefine BAZ @BAZ@
  8.  
  9. #endif // CONFIG_H

Output:

Code: include/config.h (view, download)

  1. #ifndef CONFIG_H
  2. #define CONFIG_H
  3.  
  4. #define WITH_FOO
  5. /* #define WITH_BAR */
  6.  
  7. #define BAZ 18
  8.  
  9. #endif // CONFIG_H