How to limit maximum CXX_STANDARD to prevent accidental C++17 or above code

CMake doesn’t provide a way to limit the language standard. It only provides a way to say “this thing needs at least language standard XXX”. A target can have a few different contributors to its required language standard, and CMake chooses the lowest language standard that satisfies all those requirements. It does not give you a way to say “don’t set the language standard to anything higher than XXX”.

That part of the book is going to be updated in the next edition (I’m actually in the middle of updating that specific part right now). With C++20 modules now potentially in the picture, things get a whole lot more complicated. You used to (typically) be able to get away with mixing different language standards in the one build, but you can’t any more once C++20 modules are involved. You need to have the same language standard used throughout or you run into problems with BMIs (built module interfaces). Not directly relevant to your specific query, but you’ll find the recommended pattern of setting the three CMAKE_... variables for the language standard and extensions will be more involved going forward.

1 Like