CMake: override subdirectory options

Last year I moved Monkey build system to CMake and when I started Fluent Bit I did it in the same way, a great experience.

Due to the nature of the projects mentioned where they can be build as libraries, I found that overriding the sub directories options was not too straightforward: if I have a project A with some options they should be listed like this in the CMakeLists.txt file:

option(WITH_FEATURE_AA  "Enable feature AA"   ON)
option(WITH_FEATURE_BB  "Enable feature BB"   OFF)

Now if I started a project B and I have included project A in a subdirectory, the files hierarchy should be:

project_B/
project_B/CMakeLists.txt
project_B/project_A/
project_B/project_A/CMakelists.txt

When building project_B based on it CMakeLists.txt rules, I may want to override some default options values of project_A, documentation is a bit confusing and you are likely to waste time trying to determinate why you cannot override the values, the guilty is the CMake Cache. As a workaround I found that building a simple macro in project_B/CMakeLists.txt solves the problem without complexity:

macro(SET_OPTION option value)
  set(${option} ${value} CACHE INTERNAL "" FORCE)
endmacro()

# Let's override the values
SET_OPTION(WITH_FEATURE_AA  OFF)
SET_OPTION(WITH_FEATURE_AA  ON)

# Now join the subdirectory
add_subdirectory(project_A)

If you want to see a working code example, checkout the following GIT repository:

http://github.com/edsiper/cmake-options