Creating a C/C++ Code Formatting tool with help of Clang tools

In this tutorial, we will be discussing how to create a C/C++ code formatting tool using Python and clang-format. This tool automatically formats all C/C++ source files in a project directory according to specified coding standards.

Installation Requirements:

sudo apt install python3
sudo apt install clang-format

How It Works

The tool works by recursively scanning directories for C/C++ files and applying clang-format to each file. It uses Python's os.walk() to traverse directories and identifies source files by their extensions.

Example: Python Code Formatter Script

Create a Python file named format_code.py in your project directory −

import os

# Define C/C++ file extensions to format
cpp_extensions = (".cxx", ".cpp", ".c", ".hxx", ".hh", ".cc", ".hpp")

# Walk through all directories starting from current directory
for root, dirs, files in os.walk(os.getcwd()):
    for file in files:
        if file.endswith(cpp_extensions):
            file_path = os.path.join(root, file)
            os.system("clang-format -i -style=file " + file_path)
            print(f"Formatted: {file_path}")

Creating Configuration File

Generate a .clang-format configuration file using Google style as base −

clang-format -style=google -dump-config > .clang-format

Place this .clang-format file in your project's root directory. You can customize the formatting rules by editing this file.

Example: Sample C Code Before and After Formatting

Here's how the tool transforms poorly formatted C code −

// Before formatting (messy_code.c)
#include<stdio.h>
int main(){int x=10;
if(x>5){printf("Greater than 5\n");}
else{printf("Less than or equal to 5\n");}return 0;}
// After formatting (formatted by clang-format)
#include <stdio.h>

int main() {
    int x = 10;
    if (x > 5) {
        printf("Greater than 5\n");
    } else {
        printf("Less than or equal to 5\n");
    }
    return 0;
}

Usage Steps

  1. Save the Python script as format_code.py in your project directory
  2. Create .clang-format configuration file in the same directory
  3. Run the formatter: python3 format_code.py
  4. All C/C++ files in the project will be automatically formatted

Key Features

  • Recursive Processing: Formats files in all subdirectories
  • Multiple Extensions: Supports all common C/C++ file extensions
  • In-place Formatting: The -i flag modifies files directly
  • Configurable Style: Uses .clang-format for consistent formatting rules

Conclusion

This Python-based code formatter provides an efficient way to maintain consistent coding style across C/C++ projects. By combining Python's file system traversal capabilities with clang-format's powerful formatting engine, you can ensure all source code follows your team's coding standards.

Updated on: 2026-03-15T12:46:30+05:30

274 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements