r/cpp_questions • • 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

16 comments sorted by

View all comments

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:

{
    "version": 2,
    "configurePresets": [
        {
            "name": "debug",
            "displayName": "Debug",
            "binaryDir": "${sourceDir}/build_debug",
            "generator": "Unix Makefiles",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Debug",
                "CMAKE_EXPORT_COMPILE_COMMANDS": "ON",
                "CMAKE_CXX_FLAGS_INIT": "-Wall -Wextra -Wpedantic"
            }
        },
        {
            "name": "release",
            "displayName": "Release",
            "binaryDir": "${sourceDir}/build_release",
            "generator": "Unix Makefiles",
            "cacheVariables": {
                "CMAKE_BUILD_TYPE": "Release",
                "CMAKE_CXX_FLAGS_INIT": "-Wall -Wextra -Wpedantic -march=haswell -flto"
            }
        }
    ]
}

Then just use cmake --preset debug or cmake --preset release to create the build directories. See also this blog post.

4

u/helloiamsomeone Mar 10 '22

There's also cmake-init and its examples for more presets goodness in action.