Getting started with Clang-Format Style Options

Horatiu Prica Horatiu March 18, 2020

Getting started with Clang-Format Style Options can be a real uphill battle at times due to the multitude of options and the slow process of discovering the best style for you and your team. This is why Clang Power Tools now has a built-in configurator for quickly finding the code style that best fits you.

In this post, we’ll take a look at what are Clang-Format Style Options, how they function, and how you can configure them using our tool to best suit your code format style.

  1. What are Clang-Format Style Options
  2. Creating a .clang-format file for the first time
  3. Creating a .clang-format file with the Clang-Format Configurator
  4. Video tutorial
  5. Conclusion

💡 Use the Clang-Format Detector to automatically find the best matching Clang-Format Style for your code.

What are Clang-Format Style Options

Clang-Format Style Options are flags that are supported by the ClangFormat tool, which became the de-facto standard to format C++ code.

Clang offers the option to use one of the predefined styles (LLVM, Google, Chromium, Mozilla, WebKit, Microsoft) or to create a custom configuration by using the given flags.

In the next sections, we’ll take a look at how you can create a .clang-format file without and with the configurator.

Creating a .clang-format file for the first time

Before using the Clang-Format Configurator, let’s take a look at a .clang-format file and how you would create one without the configurator.

The .clang-format file uses YAML format and can be made from scratch or by passing a command to clang-format.exe to create a predefined one.

Sample of a .clang-format file

StyleOption1: value1
StyleOption2: value2
# A comment.
…

For our first example, we’ll look at how to make a predefined .clang-format file. To create a predefined file pass the command below via Command Prompt or PowerShell to clang-format.exe.

clang-format.exe -style=llvm -dump-config > .clang-format

After running the command to generate a predefined configuration, a file is generated next to the clang-format executable. The file should look like this:

---
Language:    	Cpp
# BasedOnStyle:  LLVM
AccessModifierOffset: -2
AlignAfterOpenBracket: Align
AlignConsecutiveMacros: false
AlignConsecutiveAssignments: false
...

Now that we have a .clang-format file, we need to place it in the project folder or in any parent folder of the file you want to format. clang-format.exe searches for the config file automatically starting with the folder where the file you want to format is located, all the way to the topmost directory.

Go back to the Command Prompt or PowerShell and run the command below.

clang-format.exe -style=file 'D:\ProjectFolder\FileToFormat.cpp'

💡 Certain IDEs can use clang-format as an alternative code formatter.

Your formatted code using the predefined LLVM style is displayed in the command window.

The time has come to create a custom .clang-format file. To do this, remove all the flags you don’t want to use for formatting from the previously created predefined clang-format.exe. In our case, we’ll keep the Language(mandatory flag) and IndentWidth flags for simplicity.

---
Language: Cpp
IndentWidth: 8

Go back to the Command Prompt or PowerShell and run the format command again.


Code Sample

// member initialization

#include <iostream>
using namespace std;

class Circle {
  double radius;
  public:
  Circle(double r) : radius(r) { }
  double area() {return radius*radius*3.14159265;}
};

Code Sample format IndentWidth: 8

// member initialization

#include <iostream>
using namespace std;

class Circle {
          double radius;

        public:
          Circle(double r) : radius(r) {}
          double area() { return radius * radius * 3.14159265; }
};

Now that we formatted our code using predefined and custom styles, you realize that it is not the style you were looking for. What now?

Clang Power Tools Format Editor - wrong format

To solve this problem, we’ll continue to add/remove/change the values of specific Style Options and rerun the format command until we get the style we want. This is the point when you’ll begin asking yourself a few questions:

  1. How did the combination of Style Options influence the format command?
  2. What does this Style Option do?
  3. How did the original file look before formatting?
  4. Is using a file comparison tool the only way to compare the effects of the format?

Clang Format File Diff

Taking these questions into consideration, you quickly begin to realize that creating a .clang-format file is a slow process, even with an IDE that supports .clang-format, you cannot properly compare the effects of format without a lot of iterations and using a comparison tool.

Creating a .clang-format file with the Clang-Format Configurator

Starting with Clang Power Tools version 5.6, we implemented a new easier way of configuring Style Options and creating .clang-format files.

To access the Configurator go to Settings > Format tab > Clang-Format Editor > Clang-Format Configurator

Clang Format Editor

  1. Code Editor
    • ▪ Input - write the code you want to format
    • ▪ Output - see the effects of the Clang-Format Style Options on your code
  2. Style Options
    • ▪ Option - name, the value, On/Off switch to add or remove it to the .clang-format file
    • ▪ Description - option description
  3. Command Buttons
    • ▪ Reset Options - reset all the style options values and disable them
    • ▪ Export .clang-format - create the .clang-format file on your local machine containing the enabled style options
    • ▪ Select Code File - select a source code file, its content is loaded in the Code Editor input

Video tutorial

Let’s begin to create a new .clang-format file with the Clang-Format Configurator.

  1. Paste the code you want to format in the Code Editor or use the Select Code File button

    Code Sample

    // member initialization
    
    #include <iostream>
    using namespace std;
    
    class Circle {
      double radius;
      public:
      Circle(double r) : radius(r) { }
      double area() {return radius*radius*3.14159265;}
    };
    
  2. Find the Style Options you want to change. For this example, we’ll use ColumnLimit, MaxEmptyLinesToKeep, ConstructorIntializerIdentWidth, and BreakBeforeBinaryOperations
    ColumnLimit: 20
    MaxEmptyLinesToKeep: 1
    ConstructorIntializerIdentWidth: 10
    BreakBeforeBinaryOperations: true
    
Flags Changed

The code has been formatted using the selected Style Options. To see the result go to the Output tab.

// member
// initialization

#include <iostream>
using namespace std;

class Circle {
  double radius;

public:
  Circle(double r)
            : radius(
                r) {
  }
  double area() {
    return radius
          * radius
          * 3.14159265;
  }
};

Conclusion

You can see how fast and painless the process of finding a format style is with the Clang-Format Editor. All you have to do now is to start experimenting and find the best fit for you.

In the upcoming releases, we’ll keep improving the Clang-Format Configurator with predefined styles, the option to import .clang-format files, and many more. So if you have any suggestions or issues to report, let us know on our GitHub.