clang-format
clang-format is a Python package that distributes the official LLVM-based code formatting utility for C, C++, C#, Java, JavaScript, JSON, Objective-C, and Protobuf. It allows users to easily install and use a specific version of the `clang-format` executable via pip. The project aims to release a new PyPI package for each major and minor release of upstream clang-format, currently at version 22.1.3.
Warnings
- breaking The `-sort-includes` option (or `SortIncludes: true` in `.clang-format` config) can reorder `#include` directives. This might break code that relies on specific include order, especially if headers have order-dependent definitions.
- gotcha While primarily a whitespace formatter, `clang-format` includes features that can make non-whitespace changes (e.g., namespace commenting, certain lambda formatting with `AlignArrayOfStructures`). Unexpected non-whitespace changes can potentially alter code semantics or introduce bugs.
- gotcha Incorrect language detection or explicit language configuration in `.clang-format` files can lead to formatting errors. For example, formatting a `.c` file with `Language: Cpp` might fail or produce unexpected results in newer versions of clang-format if `Language: C` is not also specified or implicitly handled.
- gotcha Using a `.clang-format` configuration file that contains options unsupported by the installed `clang-format` version (e.g., options from a newer clang-format version) can lead to silent failures where files are not formatted, or errors.
Install
-
pip install clang-format
Imports
- clang-format (executable)
import subprocess; subprocess.run(['clang-format', ...])
- clang_format
from clang_format import clang_format
Quickstart
import subprocess
import os
import tempfile
# Create a dummy C++ file
cpp_code_unformatted = """
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
"""
# Use a temporary file to demonstrate formatting a real file
with tempfile.NamedTemporaryFile(mode='w', suffix='.cpp', delete=False) as temp_file:
temp_file.write(cpp_code_unformatted)
temp_file_path = temp_file.name
try:
# Run clang-format on the temporary file
# The 'clang-format' command is made available in PATH by the pip installation
result = subprocess.run(
["clang-format", "-style=LLVM", temp_file_path],
capture_output=True,
text=True, # Decode stdout/stderr as text
check=True # Raise an exception for non-zero exit codes
)
formatted_code = result.stdout
print("Original code:\n", cpp_code_unformatted)
print("\nFormatted code:\n", formatted_code)
except FileNotFoundError:
print("Error: 'clang-format' executable not found. Make sure it's installed and in your system's PATH.")
except subprocess.CalledProcessError as e:
print(f"Error formatting file: {e.returncode}")
print(f"Stderr: {e.stderr}")
finally:
# Clean up the temporary file
os.remove(temp_file_path)