Anton Andreev
Anton Andreev

Reputation: 2132

CMake recursive include of modules

Is it possible to use the CMake INCLUDE command the same way as in C++.

In all my projects I have to make the same includes:

Example: CMakeLists.txt for "MyApplication"

INCLUDE("FindMyBase")
INCLUDE("FindMyGtk")

In this example FindMyGtk already has "FindMyBase" in it. So why do I need to include FindMyBase in MyApplication? Is there a way once one .cmake file has been included that it stays available for all other projects in the chain below?

Upvotes: 1

Views: 1031

Answers (1)

Fraser
Fraser

Reputation: 78458

It pretty much does do that. I visualise include as if you'd pasted the contents of the include file directly into the CMakeLists.txt file where you called it.

In your case, "FindMyBase" is called twice. This often doesn't matter - e.g. if the include file only defines functions or macros it's safe to include multiple times.

If the included file searches for components using CMake's collection of find_XXX functions, then these already do what you want. The result of the search is cached. On subsequent invocations, if this cached result shows that the component has already been found, no further searching is done.

If you want (or have) to avoid including the same file multiple times, you can add include guards to the top of the file in a similar way to C++ include guards:

if(FindMyBaseIncluded)
  return()
endif()
set(FindMyBaseIncluded TRUE)

That way, including the file multiple times is almost cost-free.

Upvotes: 2

Related Questions