DEV Community

Kien Nguyen Chi
Kien Nguyen Chi

Posted on

C++ Static Analysis Tool

Introduction

This week, I work on my Static Site Generator (SSG) - Potato Generator. I plan to implement a source code formatter for my project, which is clang-format and a linter, which is clang-tidy.

Implement the clang-format

  • Using CMD, I install clang-format by npm.
npm install clang-format
Enter fullscreen mode Exit fullscreen mode
  • Then I create .clang-format file by the command:
clang-format.exe -style=llvm -dump-config > .clang-format
Enter fullscreen mode Exit fullscreen mode
  • I download Clang Format Editor to test custom format. We can use this app to modify our format for the code. In this case, I use the default format. The app will show the options with switches to modify format (which is convenient), differences between current source code and formatted source code:
  • I run the editor on the all .cpp files and .h files in my project with style WebKit to format my code.
clang-format -i -style=WebKit *.cpp *.h
Enter fullscreen mode Exit fullscreen mode
  • If you are using Visual Studio Code, you can:
    • Install clang-format extension
    • Use Shift+Alt+F to format your current file

Implement clang-tidy

  • I install linter clang-tidy
  • After installation, I run the tool by this command on cmd
clang-tidy --checks='modernize*, readability*' filename.cpp -- -std=c++17
Enter fullscreen mode Exit fullscreen mode
  • It will show a list of warnings and errors in my code.
  • In my situation, it shows that I should replace the return type of string to auto, which I do not prefer to do, so I keep that warnings.
warning: use a trailing return type for this function [modernize-use-trailing-return-type]
    string getURL();
    ~~~~~~ ^
    auto            -> string
Enter fullscreen mode Exit fullscreen mode
  • If you are using Visual Studio Code, you can:
    • Install clang-tidy extension
    • It will automatically read through your file and show errors/warnings

Conclusion

You can take a look at by implementation and instructions to build Static Analysis Tool for C++ program with clang-format and clang-tidy in my commit.

Overall, these tools are extremely helpful to restructure the code in nice format and eliminate all the warnings and errors from the code. It is a useful tool for developers to contribute on other project in open-source world.

Top comments (0)