Search code examples
c++c++11visual-c++static-analysiscppcheck

How to configure CppCheck to discourage usage of a function


Reading CppCheck's List of Checks and the checkfunctions.h I noticed the feature:

Warn if a function is called whose usage is discouraged

I did not understand how to configure this, though. More specifically I want

  1. One of my own implemented functions to be discouraged
  2. A 3rdparty function (e.g. OpenCV's cv::imwrite()) to be discouraged. I am linking the pre-builts of this library so it would be hard (but not impossible) to change the source code to achieve it

How can I annotate these functions or how can I add them to CppCheck's list of "functions non grata"?


Solution

  • The check uses configuration. Nothing is hardcoded. Write a custom cfg file and use --library to load that.

    You can write the cfg file manually, it is xml format. Or you can use the GUI (it is not the best GUI ever but imho it works).

    If you have a function foo that is deprecated then you will write something like:

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

    You can specify a custom warning message also:

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

    For each argument that the function takes you need to provide a <arg>.

    Let me know if you have problems.