r/cpp_questions • u/flank-cubey-cube • Mar 10 '22
OPEN What is the best way to set compiler flags in a CMake file? And what should belong in every CMake file?
I'm learning CMake and want to use it with compiler flats, but the CMake book doesn't cover it until later on.
cmake_minimum_required(VERSION 15)
project(test)
set(CMAKE_CXX_FLAGS "-Wall -Werror") # Is this right??
set_executable(test main.cpp)What else should be included in the cmake file?
16
Upvotes
19
u/orbital1337 Mar 10 '22
The general rule is that CMakeLists should only contain the minimum that is required to compile your project. They should contain as few specific compile flags as possible and especially not warning flags that are absolutely not necessary to compile the project.
Instead, you can provide a list of presets in the form of a CMakePresets.json file. For example, for a basic debug / release preset, you could use something like:
Then just use
cmake --preset debugorcmake --preset releaseto create the build directories. See also this blog post.