Where to use `cmake_minimum_required`?

I would like to ask for a recommendation on how cmake_minimum_required should be used?

Until now, I have been putting cmake_minimum_required in all the CMake scripts (not only top-level ones) to advertise the minimum version needed for this particular file/script. It is useful when we want to reuse the same scripts in different projects.

However, one of my users raised this issue: Inconsistent cmake_minimum_required · Issue #592 · mpusz/mp-units · GitHub, claiming that is not the correct approach, and his rationale seems strong. In this particular case CMP0074 policy was not used for some dependencies.

What do you think about this?

1 Like

I find your usage is not wrong. It states what that specific code was tested with. And yes, that may mean that newer features are unavailable.

It makes sense to update them from time to time anyway, maybe using a version range. 3.5 is quite old.

Within a single project, I would only use it on the top-level script though.

1 Like

I would generally put cmake_minimum_required() at the top of any file that might be used on its own, and not usually anywhere else. That means the top level CMakeLists.txt needs it, but the CMakeLists.txt files in subdirectories usually wouldn’t need it. If your project provides CMake module files that it installs for other projects to use, or that other projects may use directly if consuming yours via FetchContent, those module files should also have their own cmake_minimum_required() calls at their top. If they don’t, they will be at the mercy of whatever policy settings the consuming project uses.

Outside of the above cases, I’d generally recommend against putting otherwise unnecessary cmake_minimum_required() calls in files that already have their minimum CMake version and policy settings robustly controlled by a parent. Putting them in subdirectories’ CMakeLists.txt file invites inconsistent settings and can hamper efforts by other projects that consume yours (e.g. via FetchContent). I’ve seen this in some projects, which becomes more of an issue when CMake raises the minimum CMake version at which it issues deprecation warnings (this happens periodically).

Do note that if you make a CMake module available initially without having cmake_minimum_required() at the top to control its policy settings, it may be challenging to introduce it later. Doing so make be a breaking change for projects. We’ve faced this problem with CMake’s own module files on multiple occasions. So maybe err on the side of if a CMake module file might be made public at some point, put a cmake_mimum_required() in there. The cost is a maintenance one where you’ll have more files you need to keep in sync when you want to raise the minimum version (or as @hsattler mentions, raise the maximum if you use a version range, which is also a good idea).

2 Likes