How to set warning level in CMake?

How to set a warning level for a project (and not for the whole solution) using CMake ? Should work in Visual Studio and GCC.

I found various options, but most of them either do not work or are not consistent with the documentation.

+90
cmake warning-level
Mar 03 '10 at 4:37
source share
4 answers

Here is the best solution I have found so far (including compiler checking):

if(CMAKE_BUILD_TOOL MATCHES "(msdev|devenv|nmake)") add_definitions(/W2) endif() 

This will set alert level 2 in Visual Studio. I believe that with -W2 it will work in GCC (untested).

Update from @Williams: for GCC, it should be -Wall .

+7
Mar 03 '10 at 6:23
source share

UPDATE: This answer precedes the era of modern CMake. Every sensible CMake user should refrain from CMAKE_CXX_FLAGS with CMAKE_CXX_FLAGS directly and call the target_compile_options command target_compile_options . Check out the MRT answer, which presents recommended best practices.

You can do something similar to this:

 if(MSVC) # Force to always compile with W4 if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]") string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}") else() set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /W4") endif() elseif(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) # Update if necessary set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wno-long-long -pedantic") endif() 
+82
Sep 29 '10 at 0:57
source share

In modern CMake, the following works well:

 if(MSVC) target_compile_options(${TARGET_NAME} PRIVATE /W4 /WX) else() target_compile_options(${TARGET_NAME} PRIVATE -Wall -Wextra -pedantic -Werror) endif() 

Replace ${TARGET_NAME} with the actual target name. -Werror is optional; it turns all warnings into errors.

Or use add_compile_options(...) if you want to apply it to all goals, as suggested by @aldo in the comments.

+36
Jun 15 '18 at 20:23
source share

Some CMake modules I wrote include experimental cross-platform warning suppression :

 sugar_generate_warning_flags( target_compile_options target_properties ENABLE conversion TREAT_AS_ERRORS ALL ) set_target_properties( foo PROPERTIES ${target_properties} COMPILE_OPTIONS "${target_compile_options}" ) 

Result for Xcode:

  • Set CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION attribute CLANG_WARN_SUSPICIOUS_IMPLICIT_CONVERSION (aka assembly settings β†’ warnings β†’ suspicious implicit conversions β†’ YES)
  • Add compiler flag: -Werror

Makefile gcc and clang:

  • Add compiler flags: -Wconversion , -Werror

Visual studio:

  • Add compiler flags: /WX , /w14244

communication

+23
Jun 24 '14 at 6:23
source share



All Articles