×

Search anything:

Use astyle to format C++ code

Binary Tree book by OpenGenus

Open-Source Internship opportunity by OpenGenus for programmers. Apply now.

In this article, we have presented how to use astyle tool to format C/ C++ code files and set your custom code format style.

Astyle stands for Artistic Style and is a formatting tool that helps to ensure all code files follows a strict format.

Table of contents:

  1. Install astyle
  2. Set custom format for astyle
  3. Apply astyle to code

Install astyle

In UNIX system like Ubuntu, install astyle using apt-get tool as follows:

sudo apt-get update -y
sudo apt-get install -y astyle

Set custom format for astyle

We can set custom format rules for astyle in a specific file and pass it in the astyle command to force the code files to follow our custom rules.

Open a file as follows:

vi $HOME/astyle_std

Add the following rules in the above file and save it:

--convert-tabs          # convert tabs to spaces
--indent=spaces=4       # indent is set to 4 spaces
--add-brackets          # add brackets to one line conditional statements
--max-code-length=50    # maximum column width

You can specify your custom rules based on your requirements or project requirements.

Apply astyle to code

To apply astyle to a specific code file (say code.cpp), use the following command:

astyle --style=google --suffix=none --options=$HOME/astyle_std code.cpp

This applies the code format styles specified by Google style document (see --style option) and using the --options, we pass the specific formatting rules we need over the Google format document.

You can apply to multiple files at once like:

astyle --style=google --suffix=none --options=$HOME/astyle_std 
    code1.cpp code2.cpp code3.cpp code4.cpp ...

With this article at OpenGenus, you must have the complete idea of how to apply astyle format tool to C and C++ code files.

Use astyle to format C++ code
Share this