Minimal modern CMake project — what are the must-have commands?
C++Level: IntermediateDebugging & Tools
Minimal modern CMake project — what are the must-have commands?
Hints
- Identify types, object lifetimes and compile-time decisions.
- Separate language guarantees from a particular compiler's behavior.
Answer
Minimal Project
The simplest CMake project requires only a few lines. The cmake_minimum_required
ensures compatibility, while project defines metadata used throughout the build.
cmake_minimum_required(VERSION 3.16)
project(MyProject VERSION 1.0.0 LANGUAGES CXX)
add_executable(app main.cpp)
target_compile_features(app PRIVATE cxx_std_17)
Modern C++ Standard Setting
Using target_compile_features is preferred over global CMAKE_CXX_STANDARD
because it applies only to specific targets and can require specific language features.
# Per-target (preferred)
target_compile_features(app PRIVATE cxx_std_17)
target_compile_features(app PRIVATE cxx_std_20)
# Or require specific features
target_compile_features(app PRIVATE cxx_constexpr cxx_lambdas)
# Global (legacy, avoid)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT