5

My top-level CMake project depends on some-library, which I include into my project using

add_subdirectory (some-library)

and then link against it using

target_link_libraries (my-project PRIVATE some-library)

I also want to add install (TARGETS my-rpoject ...) directives so that my project can be installed to the system via whatever build system is generated (e.g. via sudo ninja install if using the -GNinja generator).

However, if some-library also defines some install (TARGETS some-library ...) directives, they get lumped in with the installation of my project's targets, which given a few subdirectory dependencies creates a bunch of extra, needless cruft in the system's installation directories which I'd like to avoid.

How can I get CMake to exclude any install (...) targets from submodules/dependency projects added with add_subdirectory () and keep only the ones in my top-level project?

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145

1 Answers1

4

At least as of CMake 3.0, add_subdirectory () has the EXCLUDE_FROM_ALL flag that can be added to the end of the call.

add_subdirectory (some-library EXCLUDE_FROM_ALL)

This removes all targets (including installation targets) from being evaluated at build time by the default rule, meaning they won't be built unless they are explicitly specified on the command line or are otherwise depended upon by a target that is included in the default rule.

Since your top-level project's targets are inherently included in the default rule (unless you create a custom target that also specifies EXCLUDE_FROM_ALL, for example), then passing EXCLUDE_FROM_ALL to add_subdirectory () and then linking against the dependency targets will automatically build any dependencies your project needs as you'd expect but omits install targets from the default install rule.

Therefore, all that remain are your own install() targets - none of your subdirectories'.

Qix - MONICA WAS MISTREATED
  • 14,451
  • 16
  • 82
  • 145
  • 1
    Sounds nice, but doesn't work at the moment. The excluded subdir and it's targets will become un-buildable as standalone build targets, because they don't have their own project files. You'll run into `MSBUILD : error MSB1009 Project file does not exist.`. Referencing: https://gitlab.kitware.com/cmake/cmake/-/issues/18048 – Jens A. Koch May 06 '22 at 15:10
  • I don't use VS projects so this wasn't something I would have run into. Sorry :/ – Qix - MONICA WAS MISTREATED May 07 '22 at 11:36