astyle批量优化代码风格

来源:互联网 发布:侠客风云传前传优化 编辑:程序博客网 时间:2024/06/18 15:56

astyle & Google style

本文主要介绍使用astyle这个工具来批量优化我们的代码风格为Google style。

astyle

安装

Ubuntu安装: sudo apt-get install astyle

使用

Usage: astyle [options] Source1.cpp Source2.cpp […]
    astyle [options] < Original > Beautified

例如:
    astyle –style=kr your.cpp your.h
这个命令优化了your.cpp和your.h文件,优化为kr风格。

kr风格
–style=kr

namespace My_Style{int Style(){    if (flag) {        return 1;    } else {        return 0;    }}}


ansi风格
–style=ansi

namespace My_Style{int Style(){    if (flag)    {        return 1;    }    else    {        return 0;    }}}


linux风格
–style=linux

namespace My_Style{int Style(){    if (flag) {        return 1;    } else {        return 0;    }}}


gnu风格
–style=gnu

namespace My_Style{int Style(){    if (flag)        {            return 1;        }    else        {            return 0;        }}}


java风格
–style=java

namespace My_Style {int Style() {    if (flag) {        return 1;    } else {        return 0;    }}}



Google style

目前实习的公司代码采用Google style。
使用工具cpplint可以进行Google style的检查,cpplint是一个python脚本,Google使用它作为自己的C++代码规范检查工具。

安装

sudo apt-get install python-pip
sudo pip install cpplint

使用

cpplint your.cpp


使用astyle批量优化

参数

  • -p
    在操作符两边插入空格,如=、+、-等。
    如:int a=10*60;
    处理后:int a = 10 * 60;
  • -a
    大括号前一个与上一行在同一行
  • -n
    不备份文件
  • -U
    移除括号两端多余空格
  • -s#
    默认行缩进为4个空格,可以将#替换为缩进量
  • -c
    tab转换为空格
  • -S
    缩进switch中的case块,case和switch不在同一列
  • -q
    忽略所有错误

更过的参数使用可以通过 astyle -h 获取

批量格式化

使用java风格的时候,类定义中的public private protected标签均不缩进,而Google style是需要有一个空格的。暂时没有找到可以配置的参数来实现,这里采用sed来实现。
有知道的大神,还请指点一下。

#!/bin/bash#批量格式化for f in $(find ./ -name '*.c' -or -name '*.cpp' \    -or -name '*.h' -or -name '*.hpp' -type f)do    astyle --style=java -p -s4 -a -n -U -H -c -S $f > /dev/null 2>&1    sed -i 's/public:/ public:/g' `grep public: -rl $f` > /dev/null 2>&1    sed -i 's/private:/ private:/g' `grep private: -rl $f` > /dev/null 2>&1    sed -i 's/protected:/ protected:/g' `grep protected: -rl $f` > /dev/null 2>&1done

欢迎大家批评指正!

原创粉丝点击