Overriding a default option(...) value in CMake from a parent CMakeLists.txt

This question is rather old but Google brought me here.

The problem with SET(<variable name> <value> CACHE BOOL "" FORCE) is that it will set the option project wide. If you want to use a sub-project, which is a library, and you want to set BUILD_STATIC_LIBS for the sub-project (ParentLibrary) using SET(... CACHE BOOL "" FORCE) it will set the value for all projects.

I'm using the following project structure:

|CMakeLists.txt (root)
|- dependencies
   | CMakeLists.txt (dependencies)
   |- ParentLibrary
      | CMakeLists.txt (parent)
|- lib
   | CMakeLists.txt (lib)

Now I have CMakeLists.txt (dependencies) which looks like this:

# Copy the option you want to change from ParentLibrary here
option (BUILD_SHARED_LIBS "Build shared libraries" ON)
set(BUILD_SHARED_LIBS OFF)
add_subdirectory(ParentLibrary)

Advantage is that I don't have to modify ParentLibrary and that I can set the option only for that project.

It is necessary to explicitly copy the option command from the ParentLibrary as otherwise when executing CMake configuration initially the value of the variable would first be set by the set command and later the value would be overwritten by the option command because there was no value in the cache. When executing CMake configuration for the second time the option command would be ignored because there is already a value in the cache and the value from the set command would be used. This would lead to some strange behavior that the configuration between two CMake runs would be different.


Try setting the variable in the CACHE

SET(FOO_BUILD_SHARED OFF CACHE BOOL "Build libfoo shared library")

Note: You need to specify the variable type and a description so CMake knows how to display this entry in the GUI.