如何为不同的文件设置不同的警告级别?

How to set different warning levels for different files?

虽然我可以根据编译器设置不同的警告级别,例如:

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

我无法逐个文件地设置它们。

在同一目录中,我有一组文件,其名称在 ${SRC_WARN} CMake 变量中,与其他文件相比,它们需要不同的警告级别。

有没有办法用 target_compile_options 指定这样的条件?

您可以设置编译选项 (COMPILE_OPTIONS) for a single file (or group of files) using set_source_files_properties()。您可以通过添加到现有 CMake 代码来更改 ${SRC_WARN} 源文件的 COMPILE_OPTIONS

if(MSVC)
  target_compile_options(${TARGET_NAME} PRIVATE /W4 /WX)
  # Change these files to have warning level 2.
  set_source_files_properties(${SRC_WARN} PROPERTIES COMPILE_OPTIONS /W2)
else()
  target_compile_options(${TARGET_NAME} PRIVATE -Wall -Wextra -pedantic -Werror)
  # Change these files to inhibit all warnings.
  set_source_files_properties(${SRC_WARN} PROPERTIES COMPILE_OPTIONS -w)
endif()