Some dependencies don’t expect to be added to a parent project and can be less convenient to pull in with FetchContent. Install rules and tests are common areas where this shows up. There are some things you can potentially do to reduce the inconvenience, depending on the situation.
For (1), you can sometimes work around the install problems by making better use of install components. If the dependencies don’t use components with their install()
commands, you can change the default component just before you pull the dependency in by setting the CMAKE_INSTALL_DEFAULT_COMPONENT_NAME
variable. Then in your main project, omit that component from the set of components you want to include in your packages (take a look at the CPACK_COMPONENTS_ALL
variable).
Dealing with tests is harder. If you use the method above to handle the install problems, then you will avoid the need for EXCLUDE_FROM_ALL
and then you should be able to avoid the dependency problems you ran into. The dependency’s tests will still show up and be included in the main projects tests, but that is hard to avoid without the dependency providing some sort of switch to turn off adding tests. A well-structured project should ideally provide a project-specific CMake variable that can be passed down to turn tests on or off, and it should default to true if the dependency is being built on its own and false if it is not the top level project.
The output directory can be handled by unsetting CMAKE_RUNTIME_OUTPUT_DIRECTORY
just before you pull in the dependency (you can restore its value again after pulling in the dependency if something later in that CMakeLists.txt file still needs id).
As stated at the beginning, FetchContent relies on the dependency projects you pull in being structured in a way that supports them not being the top level project. If you’re in control of all those dependencies (as is often the case in company environments), it can work very well. If you’re pulling in many arbitrary dependencies from the open source world, your experiences can vary widely. Some projects take care and behave well, others are downright terrible and have little interest in improving the situation. For the latter, some people maintain their own fork or set of patches to address shortcomings in such dependencies, but you would have to decide what path makes the most sense for your situation.