设置诊断:来自 CMakeLists.txt 的插入符号

2022-01-12 00:00:00 cmake visual-studio-2017 c++

我想使用 Visual Studio 2017 中新的(更好的)诊断信息.

I would like to use the new (and better) diagnostic information from visual studio 2017.

要同时为我的所有项目启用它,我想从我的 CMakeLists.txt 中声明这个标志

To have it enabled to all my project at once I want to declare this flag from my CMakeLists.txt

我试过了

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /diagnostics:caret")

但是编译时会报错说/diagnostics:classic(这是默认值)与/diagnostics:caret 不兼容

But when compiling there is an error saying that /diagnostics:classic (which is the default value) is not compatible with /diagnostics:caret

有没有办法使用 cmake 覆盖默认值?

Is there a way to override the default value using cmake ?

推荐答案

你只需要知道 CMake 尚未正式支持的 VS 编译器选项最终会在:

You just have to know that VS compiler options that CMake does not yet officially support will end up under:

属性/C/C++/命令行/附加选项

这就是你得到的原因

cl : Command line error D8016: '/diagnostics:classic' and '/diagnostics:caret' 
                               command-line options are incompatible

但是您可以使用新的 cl 选项">VS_USER_PROPS 目标属性(版本 >= 3.8).

But you can give cl options globally with the new VS_USER_PROPS target property (version >= 3.8).

这是一个工作示例:

CMakeLists.txt

cmake_minimum_required(VERSION 3.0)

project(VSAnyFlag)

file(WRITE main.cpp "int main() { return 0; }")
add_executable(${PROJECT_NAME} main.cpp)

file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.Cpp.user.props" [=[
<?xml version="1.0" encoding="utf-8"?> 
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
    <ItemDefinitionGroup>
        <ClCompile>
            <DiagnosticsFormat>Caret</DiagnosticsFormat>
        </ClCompile>
    </ItemDefinitionGroup>
</Project>
]=])

set_target_properties(
    ${PROJECT_NAME}
    PROPERTIES
        VS_USER_PROPS "${PROJECT_NAME}.Cpp.user.props"
)    

参考

  • 使用 CMake 添加 Visual C++ 属性表

相关文章