Conditionally calling pkg_check_modules in

I have a project that search for an optional dependency using either find_package, or pkg-config, as follows in its CMakeLists.txt:

find_package (PkgConfig REQUIRED)
if (ENABLE_LEVELDB) # leveldb is searched via pkg-config
    pkg_check_modules (leveldb REQUIRED IMPORTED_TARGET leveldb)
    set (HAS_LEVELDB ON)
endif ()
if (ENABLE_GDBM) # gdbm is searched via find_package
    find_package (GDBM REQUIRED)
    set (HAS_GDBM ON)
endif ()

The project creates a myproject-config.cmake from a which for now contains the following:

find_dependency (PkgConfig)
find_dependency (gdbm)

My understanding is find_dependency(gdbm) will actually search for GDBM only if find_package(gdbm REQUIRED) has been called. What is the best way to do something similar for packages found with pkg-config?

Right now the only solution I can think of is setting a MYPROJECT_HAS_LEVELDB to ON or OFF in CMakeLists.txt and have something like the following in

      pkg_check_modules (leveldb REQUIRED IMPORTED_TARGET leveldb)
endif ()

Is there a cleaner way?

No, there’s no “memory” of such things. Your example will unconditionally search for gdbm.

This is what I do and would recommend. With the bonus comment:

if (@flag_variable@) # flag_variable

to aid those reading the resulting file otherwise littered with uncommented if (OFF) or if (ON) lines.