Odds and Ends: 10 Useful Techniques

Creating a custom ClangFormat style

How can I create a custom ClangFormat style for my C++ project?

Abstract art representing computer programming

To create a custom ClangFormat style for your C++ project, you can define your own .clang-format file with specific formatting rules. Here's how you can do it:

  1. Create a new file named .clang-format in the root directory of your project.
  2. Open the .clang-format file in a text editor.
  3. Define your custom style by specifying the desired formatting options. You can start with a predefined style as a base and then override specific rules. For example:
BasedOnStyle: LLVM
IndentWidth: 4
ColumnLimit: 100
PointerAlignment: Left
AccessModifierOffset: -4
AllowShortFunctionsOnASingleLine: None

In this example, we start with the LLVM style as a base and then customize the indentation width, column limit, pointer alignment, access modifier offset, and function formatting.

  1. Save the .clang-format file.
  2. Configure your IDE or text editor to use ClangFormat with your custom style. Many IDEs have built-in support for ClangFormat, or you can use plugins to integrate it.
  3. Run ClangFormat on your C++ source files to apply the custom formatting style.

Here's an example of how your code might look before and after applying the custom ClangFormat style:


#include <iostream>
using namespace std;

void foo(int * x) {
// ...

int main() {
cout<<"Hello, World!"<<endl; return 0; }


#include <iostream>
using namespace std;

void foo(int* x)
// ...

int main()
    cout << "Hello, World!" << endl;
    return 0;

With the custom style applied, the code is formatted according to the specified rules, such as the indentation width, pointer alignment, and function formatting.

You can experiment with different formatting options to create a style that suits your project's coding conventions. The ClangFormat documentation provides a detailed list of available options and their descriptions.

Remember to share the .clang-format file with your team members to ensure consistent formatting across the project.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved