'cmake find_package slow due to finding the same package multiple times
I have a C++ project built using CMake like this way:
- The top level project adds each sub module by calling
add_subdirectory - and each sub module add its own sub modules by calling
add_subdirectory - and in the end, the sub module calls
setup_srcfunction, wherefind_packageis called to search different dependencies. - Some of the dependencies are the same but used by different modules
- Question: I would like to avoid
find_packagefor the same dependeny multiple times for different modules, how can I do that?
To give you a big picture, here is the cmake tracing visualization for investigating this issue.

More Details
I have a C++ project built with CMake, and this project has many sub modules, which has similar project structure, and I use CMake's add_subdirectory to add each sub module and their own sub modules recursively.
In each sub module, I have a CMake function setup_src, where I call find_package for searching for this sub module's dependencies. Some of the dependencies are shared by multiple sub modules, I find the overall CMake configuration process slow (17 seconds), and I did some profiling and found the find_package for the same shared dependencies multiple times, which makes the configuration slow. For example, modA depends on find_package(gRPC) and modB also depends on find_package(gRPC), and I expected the second find_package(gRPC) either not happen or be very fast, but it turns out not the case.
I tried to avoid the second time find_package for the same dependency by using additional guard criteria in CMake since I assumed modA already found gRPC and modB doesn't have to find it again, but errors are reported by CMake saying something like CMake Error at xxxx.cmake:578 (_add_library): Target "zzz" links to target "yyy::yyy" but the target was not found. Perhaps a find_package() call is missing for an IMPORTED target, or an ALIAS target is missing?, and I know yyy is a transitive dependency for the shared dependency (gRPC in the example), but it is not clear to me how I can avoid finding the same package multiple times while not running into this issue.
Any help is appreciated. Thanks.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
