How to remove a specific compiler warning in CMake

Viewed 1543

CMake seems to append some default compiler flags such as -Wall, -Wextra and so on when generating a Makefile project. One of those default flags is -Wsign-conversion and I would like to remove it from the list. Adding the suppression flag -Wno-sign-conversion like so

target_compile_options(myTarget PRIVATE "-Wno-sign-conversion")

doesn't have any effect. What's the "modern CMake" way of doing this?

2 Answers

If you don't want to query for the compiler ID/name and/or version (which quickly becomes a mess) you can use CheckCCompilerFlag (or CheckCXXCompilerFlag). The trick here is to not check for the warning disable flag, but for the warning itself. For example:

include(CheckCCompilerFlag)
check_c_compiler_flag(-Wsign-conversion HAVE_SIGN_CONVERSION)

if (HAVE_SIGN_CONVERSION)
    target_compile_options(target_name PRIVATE -Wno-sign-conversion)
endif (HAVE_SIGN_CONVERSION)

As a side note, it is recommended to avoid setting CMAKE_C_FLAGS and/or CMAKE_CXX_FLAGS directly. If possible, please use target_compile_options to disable the warning only for the targets for which you need to do this. If you want to globally disable it use add_compile_options.

Note that if other parts of your build scripts set these flags directly you may still get the warning (for example, if someone does set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wsign-conversion")). This is one of the reasons for which you should avoid setting CMAKE_C_FLAGS and CMAKE_CXX_FLAGS directly - it becomes extremely hard to control what happens.

The order in which the options are added also matters. The following minimal examples illustrates things (assuming that example.cpp contains code that will trigger a -Wsign-conversion warning):

project(example)

add_executable(example example.cpp)
target_compile_options(example PRIVATE -Wsign-conversion)
target_compile_options(example PRIVATE -Wno-sign-conversion)

This will suppress the warning. The compiler is invoked like this: /usr/bin/c++ -Wsign-conversion -Wno-sign-conversion

We can swap the two target_compile_options calls:

project(example)

add_executable(example example.cpp)
target_compile_options(example PRIVATE -Wno-sign-conversion)
target_compile_options(example PRIVATE -Wsign-conversion)

In this case, the compiler is invoked like this: /usr/bin/c++ -Wno-sign-conversion -Wsign-conversion and triggers the warning.

I am not quite sure if this is "modern CMake" but I use something like this to set the gcc flags, directly after the cmake_minimum_required Variable.

set (CMAKE_CXX_STANDARD 17)
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-sign-conversion")
endif()
Related