Cmake:为 MSVC (Visual C++) 单独设置 C 和 C++ 代码的警告级别

Cmake: Set warning levels for C and C++ code individually for MSVC (Visual C++)

我试图在基于 cmake 的构建中单独控制 C 和 C++ 代码的编译器警告:

对于 gcc 和 clang,我可以像这样设置仅适用于 C 编译器的附加标志 TARGET_COMPILE_OPTIONS:

target_compile_options(MyLib PRIVATE 
                       $<$<AND:$<COMPILE_LANGUAGE:C>,$<NOT:$<CXX_COMPILER_ID:MSVC>>>: -Wall>)

现在我想做同样的事情,但对于 MSVC: $<$<AND:$<COMPILE_LANGUAGE:C>,$<CXX_COMPILER_ID:MSVC>>: /W4>

这不起作用——在混合 C/C++ 项目中,基于 MSVC 的构建似乎忽略了 COMPILE_LANGUAGE:C。我正在使用 Visual Studio 2019 进行测试。

有人对此有解决方案吗?
(除了为 C 代码使用单独的目标之外)

... it seems COMPILE_LANGUAGE:C is ignored by MSVC-based builds in mixed C/C++ projects.

是的,CMake documentation证实了你的结论:

Note that with Visual Studio Generators and Xcode there is no way to represent target-wide compile definitions or include directories separately for C and CXX languages. Also, with Visual Studio Generators there is no way to represent target-wide flags separately for C and CXX languages. Under these generators, expressions for both C and C++ sources will be evaluated using CXX if there are any C++ sources and otherwise using C. A workaround is to create separate libraries for each source file language instead

作为分离 C 和 C++ 代码的 targets 的替代方法,您可以分离源列表,并应用 sources 的属性:

set(MY_LIB_C_SOURCES ...)
set(MY_LIB_CXX_SOURCES ...)

add_library(MyLib ${MY_LIB_C_SOURCES} ${MY_LIB_CXX_SOURCES})

# Set properties only for C source files
set_source_files_properties(${MY_LIB_C_SOURCES} PROPERTIES
  COMPILE_OPTIONS "$<NOT:$<CXX_COMPILER_ID:MSVC>>: -Wall>"
)