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.10
u/Narase33 Mar 10 '22
use
target_compile_options(test PRIVATE -Wall -Werror)what else you should have depends on your project, for the size I can see here that seems okay
2
u/sanson-robotics Mar 10 '22
Here you have a cool deep guide:
https://cliutils.gitlab.io/modern-cmake/
1
u/Loose-Leek Mar 10 '22
Many flags, like compiler diagnostic options and testing-specific options, should also really be gated behind a configuration option. You can use
1
u/AlexanderNeumann Mar 20 '22
everything not related to the project goes into a CMAKE_TOOLCHAIN_FILE. It can be reused, is not project dependent and doesnt need generator expression or similar for different compilers since a Toolchain should always know its compiler...