clang-format
Format C/C++/Objective-C code automatically
TLDR
Format a file and print the result to stdout
Format a file in-place
Format a file using a predefined coding style
Format a file using the .clang-format file in one of the parent directories of the source file
Generate a custom .clang-format file
SYNOPSIS
clang-format [options] [files...] | code
PARAMETERS
-assume-filename=string
Filename for style lookup when reading stdin
-clear-filter-cache
Clear style filter cache
-cursor=file:line:column
Cursor position for editor integration
-dump-config
Dump config options to stdout
-fallback-style={llvm|google|...}
Default style if file lookup fails
-F filename
Output file with XML replacements
-help
Show help
-i
Edit files in place (stdin if no files)
-length=N
Format range of N columns with -offset
-lines=file1:line1-line2,file2:...
Format specific line ranges
-offset=N
Start range formatting at offset N
-output-replacements-xml
Output XML replacements to stdout
-sort-includes
Sort #include directives
-style={llvm|file|...}
Specify coding style
-v
Verbose mode
DESCRIPTION
clang-format is a powerful tool from the LLVM/Clang project designed to automatically format C, C++, Objective-C, Java, JavaScript, and Protobuf code according to predefined style rules. It enforces consistent coding styles across teams, reducing debates over formatting and improving readability.
It reads configuration from a .clang-format YAML file, which can be placed in the project root, user home, or specified via options. Popular built-in styles include LLVM, Google, Chromium, Mozilla, and WebKit. Custom styles allow fine-grained control over indentation, line length, brace placement, and more.
Usage is straightforward: pipe code through stdin for quick formatting, or apply to files with -i for in-place edits. It integrates seamlessly with IDEs like VS Code, Vim, and Emacs via plugins, enabling on-save formatting. Advanced features include XML replacement output for editor integration, range formatting, and include sorting.
Ideal for large codebases, it processes files rapidly and supports dry runs. While highly configurable, it may require tuning for non-standard codebases. Widely used in open-source projects like LLVM itself.
CAVEATS
Primarily for C-family languages; JavaScript/Protobuf support limited. Complex configs may need YAML expertise. No semantic understanding—purely syntactic formatting.
CONFIGURATION
Create .clang-format with clang-format -dump-config > .clang-format, then edit YAML keys like IndentWidth: 4, ColumnLimit: 80.
EXAMPLE
clang-format -i *.cpp formats all .cpp files in place.
cat file.cpp | clang-format formats stdin.
HISTORY
Introduced in LLVM 3.3 (2013) as part of Clang toolchain. Evolved rapidly with community contributions; major enhancements in LLVM 10+ for new styles and performance. Now standard in most C++ projects for CI/CD integration.
SEE ALSO
clang(1), clang-tidy(1), astyle(1)


