Skip to main content

2 posts tagged with "Coding Style Guide"

View All Tags

· 6 min read

"Formatting C/C++ Code using ClangFormat and VSCode"

Introduction

Code formatting is an essential aspect of software development that ensures that the codebase is consistent, easy to read, and maintainable.

However, manually formatting code can be time-consuming and error-prone, especially for large projects. That's where automatic code formatting tools come in.

Clang-format

Clang-format is a powerful command-line tool for formatting C and C++ code. It can automatically format code according to a predefined set of rules or a custom configuration file.

In this article, we will explore how to use clang-format with Visual Studio Code (VSCode) to automate code formatting in C/C++ projects.

Why Use Clang-format?

Clang-format is a widely used tool in the C/C++ community for code formatting.

Here are some reasons why you might want to use it in your projects:

  • Consistency: Clang-format ensures that your code is formatted consistently across your project. This is important for readability and maintainability.

  • Saves Time: Manually formatting code can be time-consuming, especially for large projects. With Clang-format, you can automate the process and save time.

  • Avoids Errors: Manual code formatting is prone to errors. With Clang-format, you can avoid common formatting mistakes and ensure that your code is correctly formatted.

Installing Clang-format

Before we can use Clang-format with VSCode, we need to install it on our system.

There are several ways to install Clang-format, depending on your operating system.

Installing Clang-format on Linux

Clang-format is usually available in the official package repositories of most Linux distributions. You can install it using your package manager.

For example, on Ubuntu, you can install "Clang-format" using the following command:

sudo apt-get install clang-format

Installing Clang-format on macOS

Clang-format is included in the Xcode developer tools. You can install Xcode from the App Store or from the Apple developer website.

Installing Clang-format on Windows

Clang-format can be installed as part of the LLVM toolchain. You can download and install the LLVM toolchain from the official website.

Once you have installed Clang-format, you can verify the installation by running the following command:

clang-format --version
Ubuntu clang-format version 14.0.0-1ubuntu1

This shall display the version of Clang-format that is installed on your system.

Configuring Clang-format

Clang-format can be configured using a variety of options, including

  • command-line arguments
  • configuration files
  • editor extensions.

In this article, we will focus on using a configuration file to customize the formatting rules.

A Clang-format configuration file is a text file that specifies the formatting options for Clang-format.

The file should be named .clang-format and placed in the root directory of your project.

Here is an example configuration file:

BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 120

This configuration file specifies that the formatting style should be based on the Google C++ style guide, the indent width should be 4 spaces, and the column limit should be 120 characters.

The Clang-format documentation provides a comprehensive list of options that can be used in the configuration file.

https://clang.llvm.org/docs/ClangFormatStyleOptions.html

Using Clang-format with VSCode

Now that we have installed and configured Clang-format, we can integrate it with VSCode to automate code formatting.

Install the Clang-format extension for VSCode

The first step is to install the Clang-format extension for VSCode. You can do this by opening the Extensions panel in VSCode and searching for Clang-format.

Locate the extension from "Xaver Hellauer" and install, I have found this extension to be working perfectly with my setup.

"Clang Format VSCode Extension"

You can also use the vscode marketplace location to install the extension and also go through the documentation.

https://marketplace.visualstudio.com/items?itemName=xaver.clang-format

Configure the Clang-format extension

Next, we need to configure the Clang-format extension to use our custom formatting options.

To do this, open the VSCode settings file by selecting File > Preferences > Settings from the menu.

There are several settings that can be configured for the Clang-format extension, including the path to the Clang-format executable, the location of the configuration file, and the formatting style.

Here is an example configuration:

"clang-format.executable": "clang-format",
"clang-format.style": "file",
"clang-format.fallbackStyle": "Google",
"clang-format.formatOnSave": true,
"clang-format.formatOnType": true,
"clang-format.arguments": [
"-assume-filename=${workspaceFolder}/.clang-format"
]

This configuration specifies that:

  • The Clang-format executable should be called "clang-format"
  • The formatting style should be based on the configuration file in the root directory of the project
  • The fallback style should be the Google C++ style guide.
  • The "formatOnSave" and "formatOnType" options enable automatic formatting when the file is saved or typed in.
  • Finally, the "arguments" option specifies the path to the configuration file.

Use Clang-format to format code

Once the Clang-format extension is installed and configured, you can use it to format code in your project.

To format a single file, simply open the file in VSCode and press the "Format Document" shortcut (usually Ctrl+Shift+I).This will format the file according to the rules specified in the configuration file.

To format the entire project, you can use the "Format Document" command on the root folder of the project. This will format all files in the project according to the same rules.

Conclusion

Clang-format is a powerful tool for automating code formatting in C/C++ projects. With the help of the Clang-format extension for VSCode, you can easily integrate it into your development workflow and save time and effort on manual formatting. By customizing the configuration file, you can ensure that your code is formatted consistently and according to your preferred style guide.

· 4 min read

What is source code formatting

Source code formatting refers to the process of organizing and structuring the code in a consistent and readable manner. It involves adding whitespace, indentation, and line breaks to make the code more visually appealing and easier to understand.

Proper source code formatting can improve the readability and maintainability of the code, as well as make it easier to debug and modify.

Different programming languages and development environments may have different conventions and best practices for source code formatting.

There are several tools available that can automate source code formatting, such as code editors, integrated development environments (IDEs), and code formatter plugins.

These tools can apply formatting rules automatically or allow developers to customize formatting settings to match their preferences.

Example: Poorly formatted C Code

Below is an example of poorly fomatted source code:

#include<stdio.h>
int main(){
int i,j,k;
for(i=1;i<=5;i++){
for(j=1;j<=5-i;j++)
printf(" ");
for(k=1;k<=i;k++)
printf("* ");
printf("\n");
}
return 0;
}

As you can see, the code lacks proper indentation, making it harder to read and understand the structure of the loops.

Additionally, there is no spacing between the function arguments, making it harder to see where one argument ends and the next begins.

Example: Well formatted C Code

Below is the same code formatted in a more readable manner:

#include <stdio.h>

int main() {
int i, j, k;

for (i = 1; i <= 5; i++) {
for (j = 1; j <= 5 - i; j++) {
printf(" ");
}

for (k = 1; k <= i; k++) {
printf("* ");
}

printf("\n");
}

return 0;
}

Here, the code is properly indented and uses consistent spacing to make it more readable.

The code is also broken up into smaller, more manageable chunks, making it easier to understand how the loops and print statements are related.

Advantages of source code formatting

Following are the advantages of source code formatting:

Improved readability

Proper source code formatting can make code easier to read and understand, which can save time and effort during development and maintenance.

Consistency

Consistent source code formatting can help ensure that all code written by a team follows the same conventions, making it easier to collaborate on projects.

Maintainability

Proper source code formatting can make code easier to modify and update, which can help reduce errors and make the code more flexible and adaptable.

Debugging

Well-formatted code can make it easier to identify and fix bugs, as it can help pinpoint the location of issues more quickly.

Compliance

Proper source code formatting can help ensure compliance with coding standards and best practices, which can be important for certain industries or regulatory requirements.

Efficiency

Source code formatting tools and automation can help save time and effort by automating formatting tasks, which can allow developers to focus on other aspects of software development.

Professionalism

Proper source code formatting can make code look more professional and polished, which can help build trust and confidence in the software product.

Common code formatting tools

Below table shows some of the most common code formatting tools and the programming languages they support:

ToolSupported Languages
PrettierJavaScript, TypeScript, CSS, HTML, JSON, Markdown, GraphQL, YAML
BlackPython
Clang-FormatC, C++, Objective-C, ProtoBuf
RuboCopRuby
SQL FormatterSQL
ESLintJavaScript, TypeScript
GofmtGo
SwiftFormatSwift
RustfmtRust
ScalafmtScala
TerraformHashiCorp Configuration Language (HCL)
note

Please note that some of these tools may support additional languages beyond what is listed here. Additionally, there may be other code formatting tools available that support different programming languages.