How to set the warning level for a project (not the whole solution) using CMake? Should work on Visual Studio and GCC.
I found various options but most seem either not to work or are not consistent with the documentation.
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()
My colleague suggested an alternative version:
target_compile_options(${TARGET_NAME} PRIVATE
$<$<CXX_COMPILER_ID:MSVC>:/W4 /WX>
$<$<NOT:$<CXX_COMPILER_ID:MSVC>>:-Wall -Wextra -pedantic -Werror>
)
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 targets as suggested by @aldo in the comments.
Also, be sure to understand the difference between PRIVATE
and PUBLIC
(public options will be inherited by targets that depend on the given target).