Using astyle to format code

As you know, we had our coding style which everyone should follow, and also we had the cpplint tool to check if we had followed the rule, but we do not have a tool to check and transfer our code to the desired style code. Then there comes astyle:

Astyle is a tool which can automatically format our code and make most of the code fit our coding style. As from the website: "Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C++/CLI, Objective‑C, C# and Java programming languages."

Astyle can be installed both in windows and linux.It can also be integrated as a third party tool to format the code.

Below I would like to introduce its usage in Qt creator and Linux command line.

 

Qt creator can be used to generated part of the code, but it have its own style, which it's different from the google style which we use, it's tedious to change it by hand. Luckily, Qt creator had integrated astyle as part of the  plugin Beautifer. Here is the step to use astyle in Qt creator( The Qt creator I demoed here isQt Creator 3.3.0 (opensource) version).

  1. Click "Help"->"About plugin", check in  Beautifier.and restart the Qt creator.



2. Click "Tools"->"Options", you will see "Beautifier" is shown:


3. Download Astyle windows version which is a green software, unzip the package and browse to the Astyle.exe as above,check use the default .astylerc file and use customized style and edit it:



After the above three steps, you can use astyle to format the code in your Qt creator by click as follows or create your own customized shortcut:



Here is an example before and after using astyle:


In Linux, you can use astyle the same way, download the linux version and install to you $HOME, create a .astylerc file under your $HOME folder, customize it as:

#short option for command line uses: -A14s4SYk1fpHcn
# Predefined style option -A14
--style=google
 
# Indent using 4 spaces per indent. Don't use tab -s4
--indent=spaces=4
 
 
# Indent 'switch' blocks so that the 'case X:' statement are
# indented in the switch block. -S
--indent-switches
 
#Indent C++ comments beginning in column one. -Y
--indent-col1-comments
 
#Attach a pointer or reference operator (*, &, or ^) to either the variable type left -k1
--align-pointer=type
 
# Pad empty lines around header blocks (eg. 'if', 'while' ...) -f
--break-blocks
 
# Insert space padding around operators. -p
--pad-oper
 
#Insert space padding between a header (e.g. 'if', 'for', 'while'...) and the following paren -H
--pad-header
 
# Converts tabs into spaces in the non-indentation part of the line -c
--convert-tabs
 
# Do not retain a backup of the origional file -n
--suffix=none

Then you can use it like this:

for what more astyle can do, you can referhere.

猜你喜欢

转载自blog.csdn.net/gigglesun/article/details/60475786