首页 > 解决方案 > 如何为不同的文件设置不同的警告级别?

问题描述

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

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

标签: cmakecompiler-warningswarning-level

解决方案


COMPILE_OPTIONS您可以使用 为单个文件(或文件组)设置编译选项 ( ) set_source_files_properties()。您可以通过添加到现有的 CMake 代码来更改源文件COMPILE_OPTIONS${SRC_WARN}

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()

推荐阅读