c++ - 如何将 gcc 警告转储为结构化格式?

标签 c++ gcc g++ compiler-warnings compiler-flags

像许多人一样,我在构建项目时会遇到大量警告标志。
由于并非所有警告标志都是有害的,因此编译变得嘈杂。

“未使用的变量”、“隐藏初始化列表中的成员”、“缺少开关默认值”等警告对记录都很重要,但它们在构建过程中造成太多困惑,很难发现重要警告。

给定一个大型项目,构建语句中可能混杂着数以千计的警告,之后的解析变得很麻烦。在代码中维护编译器编译指示和推送/弹出警告同样不可取。

如何以结构化格式转储编译器警告?
无论是 XML、JSON、YAML、CSV,有没有办法告诉编译器转储所有发出的警告?像这样的格式可以让我更有效地查看警告,并按类型、文件、数量等对它们进行排序。

最佳答案

GCC 9 添加[1]支持以 JSON 格式输出警告和错误消息,只需使用 -fdiagnostics-format=json 选项即可。

比较输出

$ gcc-9 -c cve-2014-1266.c -Wall
cve-2014-1266.c: In function ‘SSLVerifySignedServerKeyExchange’:
cve-2014-1266.c:629:2: warning: this ‘if’ clause does not guard... [-Wmisleading-indentation]
  629 |  if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
      |  ^~
cve-2014-1266.c:631:3: note: ...this statement, but the latter is misleadingly indented as if it were guarded by the ‘if’
  631 |   goto fail;
      |   ^~~~

JSON 格式的:

[
    {
        "children": [
            {
                "kind": "note",
                "locations": [
                    {
                        "caret": {
                            "column": 3,
                            "file": "cve-2014-1266.c",
                            "line": 631
                        },
                        "finish": {
                            "column": 6,
                            "file": "cve-2014-1266.c",
                            "line": 631
                        }
                    }
                ],
                "message": "...this statement, but the latter is misleadingly indented as if it were guarded by the \u2018if\u2019"
            }
        ],
        "kind": "warning",
        "locations": [
            {
                "caret": {
                    "column": 2,
                    "file": "cve-2014-1266.c",
                    "line": 629
                },
                "finish": {
                    "column": 3,
                    "file": "cve-2014-1266.c",
                    "line": 629
                }
            }
        ],
        "message": "this \u2018if\u2019 clause does not guard...",
        "option": "-Wmisleading-indentation"
    }
]

[1] https://developers.redhat.com/blog/2019/03/08/usability-improvements-in-gcc-9/

关于c++ - 如何将 gcc 警告转储为结构化格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36657869/

相关文章:

c++ - 如何将 gcc include 目录添加到现有的 Makefile

c - 我必须用 -lgcc 链接文件吗?

c++ - gcc 6.1 std::result_of 编译错误

c++ - 是否可以编译 c/c++ 混合源代码?

c++ - 从记录集中保存值

c++ - 函数和数组

c++ - 在 C++ 中初始化这样的 map 的更好方法是什么?

c++ - 通过删除重复代码使我的 do while 循环更整洁

c++ - 错误使用 nullptr 的编译器错误

c++ - 模板和 g++ 4.7