如何配置 CppCheck 以阻止函数的使用

How to configure CppCheck to discourage usage of a function

阅读 CppCheck 的 List of Checks and the checkfunctions.h 我注意到了以下功能:

Warn if a function is called whose usage is discouraged

虽然我不明白如何配置它。更具体地说,我想要

  1. 我自己实现的一个功能被劝阻
  2. 不推荐使用 3rdparty 函数(例如 OpenCV 的 cv::imwrite())。我正在链接这个库的预构建,所以很难(但并非不可能)更改源代码来实现它

如何注释这些函数或如何将它们添加到 "functions non grata" 的 CppCheck 列表中?

我不确定是否有通用的方法来检查所有第三方功能的使用情况。可能@Daniel Marjamäki 是回答这个问题的最佳人选。但是您是否尝试为其创建规则?

如果您希望检查函数的确切签名,您可以使用如下内容:

<?xml version="1.0"?>
<rule version="1">
    <pattern>cv::imwrite\(\)</pattern>
    <message>
        <id>discouragedFunction</id>
        <summary>The use of the function cv::imwrite is discouraged.</summary>
    </message>
</rule>

或者,如果您想要 通用方面的更多内容 ,您可以这样:

<?xml version="1.0"?>
<rule version="1">
    <pattern>cv::[_a-zA-Z][_a-zA-Z0-9]+\(\)</pattern>
    <message>
        <id>discouragedFunction</id>
        <summary>The use of the function opencv functions are discouraged.</summary>
    </message>
</rule>

检查使用配置。没有什么是硬编码的。编写自定义 cfg 文件并使用 --library 加载它。

您可以手动编写cfg文件,它是xml格式。或者您可以使用 GUI(它不是有史以来最好的 GUI,但恕我直言,它确实有效)。

如果您有一个函数 foo 已被弃用,那么您将编写如下内容:

<function name="foo">
  <warn severity="style" alternatives="bar" reason="Deprecated"/>
  <arg nr="1"/>
</function>

您还可以指定自定义警告消息:

<function name="foo">
  <warn severity="warning">Do not use foo(). Use bar() instead.</warn>
  <arg nr="1"/>
</function>

对于函数接受的每个参数,您需要提供 <arg>.

如果您有任何问题,请告诉我。