Override default value (...) in CMake from parent CMakeLists.txt

I am trying to include several third-party libraries in my source tree with minimal changes to their build system for easy updating. They all use CMake, just like me, so in my own CMakeLists.txt I can use add_subdirectory(extern/foo) for libfoo.

But foo CMakeLists.txt compiles a test harness, builds documentation, a shared library that I don't need, and so on. The authors of libfoo had the forethought to manage these parameters - for example, option(FOO_BUILD_SHARED "Build libfoo shared library" ON) , which means that I can install them through the CMake command line. But I would like to do this by default and override through the command line.

I tried to do set(FOO_BUILD_SHARED OFF) to add_subdirectory(extern/foo) . This leads to the fact that you are not trying to create a shared library during the second and subsequent assembly attempts, but not during the first one, which I really need to speed up.

Is this possible, or do I need to support forked CMakeLists.txt for these projects?

+52
c ++ build-process build cmake
Sep 22 '10 at 6:13
source share
2 answers

Try setting the variable to CACHE

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

Note. You must specify the type of variable and description so that CMake knows how to display this entry in the GUI.

+64
Sep 22 '10 at 12:41
source share

This question is pretty old, but Google brought me here.

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

I use 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) that 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) 

The advantage is that I do not need to modify the ParentLibrary and that I can only set the option for this project.

It is necessary to explicitly copy the option command from ParentLibrary as otherwise, when executing the CMake configuration, initially the value of the variable will be set first with the set command and then the value will be overwritten with the option command since the cache. When configuring CMake a second time, the option command will be ignored, because the cache already has a value and the value from the set command will be used. This may lead to some strange behavior that the configuration between the two CMake launches will be different.

0
Jan 28 '19 at 15:14
source share



All Articles