How to selectively remove entries from the CMake cache from the command line

Just a short cmake tip today...
You probably know that with "cmake -DSOME_VARIABLE=foo" you can give variables to cmake.
Now, sometimes, e.g. if the wrong version of a package has been found, e.g. a wrong Qt, you want to remove the wrong entries for Qt from the CMake cache again (because otherwise cmake doesn't search again).

There are at least three ways you probably already know:

  • run cmake-gui (or make edit_cache) to open the "cache editor", i.e. the GUI for cmake
  • the "Holzhammer" method: simply remove the complete cache or build directory and start again
    and delete the entries you don't want there
  • open CMakeCache.txt in a text editor and edit it manually

There's another way to do which you maybe did not know yet.
Additionally to "-D" (define variable) cmake has also "-U" (undefine variable), which you can use to remove entries from the cache.
It goes like that: $ cmake -U\*QT\* .

(just using "." works if your current directory is the toplevel build directory, i.e. where the CMakeCache.txt is located)

So, -U takes as argument a globbing expression and removes everything which matches the globbing expression from the cache. So the example above will remove all entries containing "QT" in their name from the cache and it will be searched again.