Home > OS >  CMake Treat Warnings as Errors
CMake Treat Warnings as Errors

Time:08-03

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.

CodePudding user response:

Treating warnings as errors is a good practice for CI systems with a fixed and predictable toolchain, but it is inappropriate to force on all users. Many are likely using a different toolchain with different sets of warnings and sensitivities for those warnings. Enabling -Werror by default causes broken builds for your consumers and is a bad practice.

Notably, this exact issue was the source of one major debacle in the last year in the Linux kernel: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=b339ec9c229aaf399296a120d7be0e34fbc355ca

It is also prohibited by the Gentoo packaging archives (important because it is a source-based distribution): https://devmanual.gentoo.org/ebuild-writing/common-mistakes/index.html

Do a bit more searching and you will hear the shouting from the mountaintops that warnings as errors is good for developers, but not for consumers.

The best way to do this, then, is to set the new (as of CMake 3.24) variable CMAKE_COMPILE_WARNING_AS_ERROR set to ON only when you know it is safe to do so. That is to say, it should not be on by default.

There are many good ways to set this up:

  1. You could add it to the cacheVariables section of a preset
  2. You could set it to ON in a toolchain file
  3. You can simply pass it at the command line when you want to toggle it on or off.

Speaking as someone who regularly uses top-of-tree compiler builds, where warnings break frequently, hard-coded warnings-as-errors is a blight. It forces me and countless other package maintainers, devops teams, and so on, to patch your build.

CodePudding user response:

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 [...])
  • Related