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 -Wpedantic -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 -Wpedantic -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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…