cmakeoverridingsubproject

How can I prevent targets from added subdirectories of external dependencies from being built in CMake?


The structure of my project:

- CMakeLists.txt
- my_src
- extern     
  - CMakeLists.txt
  - dir1 
  - dir2

"extern" is from a third_party repo. "extern/CMakeList.txt" added "dir1" and "dir2" with "add_subdirectory()" command.

Now I want to remove "dir1" from being built. But "extern/CMakeList.txt" doesn't provides cmake option/switch for adding "dir1" or not.

So is there a better or formal solution for this situation?

I searched with google, the best solution I got is to patch the "extern" project, which is not a solution I prefer, since in this project, the extern directory is not tracked in version control and needs to be setup up manually, and I don't want to add such extra steps for other users (team members and customers) trying to build the project.


Solution

  • If your goal is actually to prevent those subdirectories from getting added (which would prevent targets added in those subdirectories' CMakeLists.txt files from getting build configuration generated), aside from modifying the CMakeLists.txt file of the external project yourself before generating the buildsystem, and/or asking the maintainer of that external project to add such options to configure whether those subdirectories of its get added, I don't think there's anything you can do.

    But from what I read (you said "Now I want to remove "dir1" from being built." (which is a little ambiguous in terms of terminology)), your goal is just to prevent the targets added in those subdirectories from getting built. Assuming they're just getting built because you're running a build command that doesn't pick specifically which targets to build (I.e. assuming you're building the "all" target), in that case, I think what you can do is set the EXCLUDE_FROM_ALL directory property for those subirectories to a truthy value for each target that you don't want to get built with the "all" target (or individually set the EXCLUDE_FROM_ALL target property for those targets added in those subdirectories). Ex.

    add_subdirectory(extern)
    set_property(DIRECTORY extern/dir1 PROPERTY EXCLUDE_FROM_ALL YES)
    set_property(DIRECTORY extern/dir2 PROPERTY EXCLUDE_FROM_ALL YES)
    

    Note that add_subdirectory itself has an EXCLUDE_FROM_ALL argument that is just a convenience way to set the corresponding directory property for the added subdirectory, but I'm not sure if that's uesful here.