Find parent project in subprojects using find_package

My project consists of a library and example programs.
The library generates a mylibrary-config.cmake in the binary directory using an export set.

My example programs are individual CMake projects calling find_package(mylibrary MODULE REQUIRED).

├── CMakeLists.txt
└── examples
    ├── a
    │   └── CMakeLists.txt
    └── b
        └── CMakeLists.txt

My goal is to build these example programs as part of my build to integrate them into tests.

After creating mylibrary-config.cmake in the CMakeLists.txt of the library, I use add_subdirectory to include the example programs.
However, this fails as they cannot find mylibrary-config.cmake.

Why does this fail, and how can I make my root project visible without modifying the CMakeLists.txt of the example programs?

The export file is written at generation time (or is partial during the build; I don’t remember exactly). It’s better, IME, to add these as tests rather than add_subdirectory. VTK does it here.

Also note that by doing find_package(mylibrary MODULE REQUIRED), you’re explicitly instructing the find_package command to use module mode (where it’s looking for Findmylibrary.cmake only), while your library is producing a package config file mylibrary-config.cmake.

Producing the package config file is the better way of doing things, but you should consume this in a way which supports it; that is, drop the MODULE parameter from the find_package call.

@Angew Thanks for noticing this. I actually meant to write find_package(mylibrary CONFIG REQUIRED).

The library only generates a CMake config, so I enforce finding the config in the example programs.