Skip to content

Clang Formatting

Nick Charron edited this page May 3, 2021 · 5 revisions

Auto-format

We use Clang formatting to ensure consistent C++ formatting before pushing to Github. There are two ways to run clang formatting described here.

Setting up a pre-commit hook:

The pre-commit hook will ensure that clang-format runs whenever you commit - if formatting changes are required it will give you the option to apply them as a patch.

Instructions for testing auto format:

  • Clone the repo (e.g., clone into ~/project_dir)
  • Install clang-format-6.0 (sudo apt install clang-format-6.0)
  • Navigate to the .git/hooks folder (~/project_dir/ros_package_template/.git/hooks)
  • Create a file named 'pre-commit' inside the project_dir/.git/hooks folder, and copy the contents of this into it.
  • Create a file named 'apply-format' inside of the project_dir/.git/hooks folder, and copy the contents of this into it.
  • Make both of the shell scripts executable (chmod +x ~/project_dir/.git/hooks/[apply-format/pre-commit])
  • Change the formatting in one of the source files (e.g., add spaces)
  • Test commit (e.g., git commit -m "test commit")
  • You should receive a message in the terminal which shows you the proposed changes from clang-format and gives you the option to patch them into the commit
  • Push back to master to verify

Auto formatting with Atom

The clang format git hook only formats new changes to the code. If you want to format all your existing code, you can do this in Atom (and probably many other editors). Here are some instructions for doing this in Atom.

  • Open Atom
  • Go to edit -> preference -> install
  • Search for clang-format and click install
  • After install, you should be able to go into packages -> Clang Format and hit format. Do this step with all your files you want to format.

Auto formatting with VS Code

To format your existing code in VS code without any hidden settings folder, do the following:

  • Open VS Code
  • Go to the 'Extensions' tab and click on the 'Manage' icon in the bottom right corner of the 'C/C++' extension (if this extension has not be installed, please install using VS code's Extensions Marketplace)
  • Go to 'Extension Settings'
  • Navigate to 'C_Cpp:Clang_format_fallback Style'
  • Within the space provided, enter 'Google'
  • Navigate to C_Cpp: Clang_format_sort Includes and set to 'false' (read docs on our header formatting)
  • After this, you may right-click anywhere in your document and select 'Format Document'
Clone this wiki locally