c++cmakecompiler-warnings

Treat compiler warnings as errors


How can I configure CMake to treat compiler warnings as errors during the build?

I am aware of the possibility to manually configure command line options for the compiler like -Werror through commands like target_compile_options, but I would prefer a portable solution that does not require fiddling with tool-dependent options.


Solution

  • This can be configured in CMake version 3.24 and higher via the COMPILE_WARNING_AS_ERROR target property.

    For example, to enable warnings as errors for the my_app target you could write:

    set_property(TARGET my_app PROPERTY COMPILE_WARNING_AS_ERROR ON)
    

    You can also set a global default for all targets in your project via the CMAKE_COMPILE_WARNING_AS_ERROR variable:

    set(CMAKE_COMPILE_WARNING_AS_ERROR ON)
    
    add_executable(my_app1 [...])
    add_executable(my_app2 [...])
    add_executable(my_app3 [...])
    

    If a user finds it annoying that this is set in the CMakeLists.txt file, they can still override it using the --compile-no-warning-as-error configure option.