2

I've a CMake project containing C and C++ files, and I have a CI set up. In the CI, I want to build my project with some additional flags to make the compiler stricter, in particular -Wall -Wextra -Werror -pedantic.

To configure the project, I'm currently repeating myself by doing this:

cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_C_FLAGS="-Wall -Wextra -Werror -pedantic" -DCMAKE_CXX_FLAGS="-Wall -Wextra -Werror -pedantic"

As I don't want these flags baked into the CMakeLists file (since this strictness is only wanted in the CI), I'm setting the flags on the configure command in the CI.

Is there any way to rewrite this command in a way where I don't need to repeat the flags?

Note: CMAKE_CPP_FLAGS does not work.

Bernard
  • 5,209
  • 1
  • 34
  • 64

1 Answers1

4

This is the exact use case for which CMake presets were invented. Please do not hard-code -Werror in your build. It is a liability for your end users who might not use the exact same compiler as you. I wrote another answer on a related question that goes into more detail.

Here's an example CMakePresets.json:

{
  "version": 4,
  "cmakeMinimumRequired": {
    "major": 3,
    "minor": 23,
    "patch": 0
  },
  "configurePresets": [
    {
      "name": "ci-gcc",
      "displayName": "CI with GCC",
      "description": "CI build with GCC-compatible compiler",
      "generator": "Ninja",
      "binaryDir": "${sourceDir}/build",
      "cacheVariables": {
        "CMAKE_BUILD_TYPE": "Release",
        "CMAKE_C_FLAGS": "-Wall -Wextra -Werror -pedantic",
        "CMAKE_CXX_FLAGS": "-Wall -Wextra -Werror -pedantic"
      }
    }
  ]
}

Then just configure your CI to build with cmake --preset ci-gcc && cmake --build build from your source directory.


As of CMake 3.24+ you should avoid writing -Werror literally, even in a preset, and prefer to set the cache variable CMAKE_COMPILE_WARNING_AS_ERROR to ON inside a preset.

Alex Reinking
  • 16,724
  • 5
  • 52
  • 86