# Conditionally calling pkg\_check\_modules in config.cmake.in

**URL:** https://discourse.cmake.org/t/conditionally-calling-pkg-check-modules-in-config-cmake-in/4265
**Category:** Usage
**Created:** [October 13, 2021, 10:18am UTC](https://discourse.cmake.org/t/conditionally-calling-pkg-check-modules-in-config-cmake-in/4265 "2021-10-13T10:18:58Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![mdorier](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/m/eb9ed0/32.png) [@mdorier](https://discourse.cmake.org/u/mdorier)
#### Post date: [October 13, 2021, 10:18am UTC](https://discourse.cmake.org/t/conditionally-calling-pkg-check-modules-in-config-cmake-in/4265/1 "2021-10-13T10:18:58Z")

</div>

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

```auto
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 `myproject-config.cmake.in` which for now contains the following:

```auto
...
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 `myproject-config.cmake.in`:

```auto
if (@MYPROJECT_HAS_LEVELDB@)
      pkg_check_modules (leveldb REQUIRED IMPORTED_TARGET leveldb)
endif ()

```

Is there a cleaner way?

---

<div class="post-metadata">

### Author: ![ben.boeckel](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/b/ea5d25/32.png) [@ben.boeckel](https://discourse.cmake.org/u/ben.boeckel)
#### Post date: [October 15, 2021, 11:58pm UTC](https://discourse.cmake.org/t/conditionally-calling-pkg-check-modules-in-config-cmake-in/4265/2 "2021-10-15T23:58:29Z")

</div>

> [@mdorier](#):
>
> My understanding is `find_dependency(gdbm)` will actually search for GDBM only if `find_package(gdbm REQUIRED)` has been called.

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

> [@mdorier](#):
>
> 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 `myproject-config.cmake.in`:

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

```cmake
if (@flag_variable@) # flag_variable

```

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