Home > OS >  Setting CMAKE_C_FLAGS and CMAKE_CXX_FLAGS to the same thing without repeating oneself?
Setting CMAKE_C_FLAGS and CMAKE_CXX_FLAGS to the same thing without repeating oneself?

Time:04-26

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 -DCXXMAKE_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.

CodePudding user response:

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.

CodePudding user response:

In your CMakeLists.txt, you can do this with an extra variable.

set(COMPILE_FLAGS "-Wall -Wextra -Werror -pedantic")

set(CMAKE_C_FLAGS ${COMPILE_FLAGS})
set(CMAKE_CXX_FLAGS ${COMPILE_FLAGS})

But you want something shorter, right?

Here's a silly solution:

set(CMAKE_C_FLAGS "-Wall -Wextra -Werror -pedantic")
set(CMAKE_CXX_FLAGS ${CMAKE_C_FLAGS})

I think it's silly because if you do something like set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wextra -Werror -pedantic"), the C flags are not included in CXX.

With CMake 2.8.12 , you can use add_compile_options. Be aware that this adds options to ALL TARGETS within the current source directory and sub-directories. I haven't tested, but I assume it would include non-C( ) targets too.

add_compile_options(-Wall -Wextra -Werror -pedantic)

For older versions of CMake, you can use add_definitions:

add_definitions(-Wall -Wextra -Werror -pedantic)

Or, my favorite, generator expressions!

  • Related