# Clang Format

### Installation in Ubuntu

```shell
sudo apt install --no-install-recommends clang clang-format
```

### Set up Git Hook

* copy file `git-clang-format` to `/usr/local/bin`&#x20;
* copy file `pre-commit` to `.git/hooks` of the repository under development
* generate `.clang-format` file in the root directory of the project

#### File: pre-commit

<pre class="language-python"><code class="lang-python"><strong>#!/usr/bin/env python
</strong>
import sys
import subprocess
output = subprocess.check_output(["git", "clang-format", "--diff"])

if output not in ['no modified files to format\n', 'clang-format did not modify any files\n']:
  sys.exit("""Error: clang format check failed. Run git clang-format -f to fix it, then commit again.
NOTE: if (and *only* if) this is a merge commit, you may skip this check with 'git commit -n'""")
</code></pre>

#### File: git-clang-format

* <https://github.com/hanzheteng/LOCUS/blob/main/scripts/clang_setup/clang/git-clang-format>

#### File: .clang-format

* Example of full configuration: <https://github.com/hanzheteng/LOCUS/blob/main/.clang-format>
* A brief example: <https://github.com/MIT-SPARK/TEASER-plusplus/blob/master/.clang-format>

### Usage

* If git hook is set, run the following command before every git commit.

```shell
git clang-format -f
```

* In addition to being used as a git hook, clang can format a single c++ file in command line.

```shell
clang-format -i -style=google *.cpp  # use google default coding style
clang-format -i -style=file *.cpp  # if .clang-format is ready (in the same dir)
```

* To disable clang formatting in certain cases.

```cpp
int formatted_code;
// clang-format off
    void unformatted_code;
// clang-format on
void formatted_code_again;
```

### References

#### Official documentation

* <https://clang.llvm.org/docs/ClangFormat.html>
* <https://clang.llvm.org/docs/ClangFormatStyleOptions.html>

#### Tutorials

* <https://www.csd.uoc.gr/~hy255/tuts/2021/clang_format_tutorial.pdf>

#### A script to automatically install clang-format and set up git hook

* <https://github.com/hanzheteng/LOCUS/blob/main/scripts/clang_setup/clang_setup.sh>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wiki.hanzheteng.com/development/google-tools/clang-format.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
