Better coding practices for your organisation using clang-tidy and clang-format.

2 min readMay 23, 2019

Formatting of the code has been one of the biggest topic of debate in tech industry for a long time. Often in big firms there are multiple teams working on a single application. Furthermore, each team has multiple developers working on different parts of the code. So how do we induce concurrency? Having a lucid format for your application not only helps for development and deployment but also for easier and cheaper maintenance practices.

Clang-Tidy is a tool developed and maintained by the Clang/LLVM community. The official documentation can be found at http://clang.llvm.org/extra/clang-tidy/.

The main purpose of clang-tidy is to provide an extensible framework for diagnosing and fixing typical programming errors, like style violations, interface misuse, or bugs that can be deduced via static analysis.

To install clang-tidy on your linux machine, use the following command:

sudo apt-get install clang-tidy

To run clang-tidy on your files, you can use the following command:

clang-tidy -checks='*' -fix test.cpp -- -std=c++11

Furthermore, clang-tidy gives you the option to manually select the checks and run them on your files. To view all the different types of checks available you can run this command:

clang-tidy --list-checks -checks='*' | grep "modernize"

To run clang-tidy on your whole project you may run the following command.

run-clang-tidy -checks='-*,performance-implicit-conversion-in-loop' -header-filter 'cpp/.*'

Although running this on your whole project is not advisable since many components may not compile after that. Running this individually on each file might be a better practice.

After using clang-tidy it is a good practice to use clang-format on your project. Clang-format is a tool to automatically format C/C++/Objective-C code, so that developers don't need to worry about style issues during code reviews.

The official documentation can be found at https://clang.llvm.org/docs/ClangFormatStyleOptions.html

As an organisation , clang-format gives you various options for formatting your code. You either choose one of the predefined styles mentioned at their website or you can write a script to enforce your own formatting style.

To run the clang-format on your whole project, you can use the following command:

find . -name '*.h' -o -name '*.cpp' | xargs clang-format -i -style=Webkit//A default formatting style of Webkit is used here

These tools not only induce better coding practices but also help you to induce strict discipline in coding style. These tools can also be included in the JenkisFile and the MakeFile of your project so that you don’t need to run them manually each time.

--

--

Atharva Kulkarni
Atharva Kulkarni

Written by Atharva Kulkarni

Avid reader, amateur writer, ukulele player. Lover of all forms of sports and esports.

No responses yet