简体   繁体   中英

CMake Treat 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM