We previously talked about the importance of applying some good practices to our code. This included topics like adding header guards and using
const when appropriate.
There is a diverse ecosystem of tooling and plugins that can analyse our code for these types of problems, and make suggestions on how we can improve it.
Many editors offer code analysis tools as standard. This includes Visual Studio.
In Visual Studio projects, static analysis can be configured under Analyze in the top menu bar. Once set up, we can then see suggestions within our source files on how we might want to modify them.
Here, we see Visual Studio asking is to consider marking a variable as
Resharper is a very powerful and popular tool for static analysis. It is not free, but does have a free trial, as well as a free license if you are in education. You can find out more on their site: Resharper C++
It comes with a Visual Studio plugin that provides inline highlighting within our source code, similar to Visual Studio's native feature. It also has a powerful UI where we can configure the checks we care about.
Here we see Resharper detectecting several issues with a basic header file.
This file is perfectly fine from a compiler's perspective, but static analysis shows it has missing header guards, unnecessary syntax, uninitialised variables and more:
CppCheck is a free, cross-platform tool that provides code analysis of our C++ projects. It comes bundled with a graphical interface, which we can load our project into, and get plenty of code suggestions.
Here, we see CppCheck has found some functions in our code that are never being used:
In general, tools like these can be a great benefit, and this is particularly true for developers less familiar with the language.
One of the main ways new developers learn languages is through a "code review" process, where more experienced developers read through their code to detect any potential issues, or to make suggestions.
This is generally not available to developers who are just learning on their own. But, static analysis tools are getting better all the time, and are quickly becoming an increasingly worthy substitute.
Become a software engineer with C++. Starting from the basics, we guide you step by step along the way
constexprkeywords to make our code better