Formatting Your C++ Code the Easy Way
Everyone has his own coding style and dislikes everyone else’s. When you have to work with code written by other people, there’s a ton of it, and their coding style differs from yours in many ways, you have to do something.
As for Psi project, we in fact have some set of code style guidelines. But still sometimes we occasionally are looking at something that’s noticeably differs from our sense of perfection.
That’s where code beautifiers come into play.
Enter Artistic Style. Small, neat and cross-platform C, C++, C# and Java code beautifier.
Installing Artistic Style
UPDATE: As of astyle-1.20 release, building it on Mac OS X is simple with provided build/Makefile.
As there is Windows-binary available on the site and a Makefile is present in the source package, it doesn’t cleanly build itself on Mac OS X, because it doesn’t know about some of osx-specific compilation flags, so it just crashes on start. And here’s that flag, if you’re curious:
-headerpad_max_install_names
You could either modify your Makefile with this knowledge, or could use a tool to produce the Makefile automatically: qmake -project && qmake. After that, it’s just a single make away from getting your hands on the binary.
I have packaged both resulting Makefile and astyle.pro in one package.
Using Artistic Style
Pipe a file to the executable, or specify file name as the argument: result is the same — code is reformatted, and is either written to the stdout, or to the file. And it also dumps an advertisement to the stderr, so don’t forget to 2> /dev/null.
The following command line gives the result most closely resembling what we describe in the Psi Code Style Guidelines:
astyle --mode=c --indent=tab=4 --brackets=linux --brackets=break-closing --min-conditional-indent=0 --pad=oper --unpad=paren && echo ""
TextMate Command
And that’s not all! To reap all benefits without having to resort to fiddling with command line, I’ve prepared a super-special limited edition TextMate command. Grab it while it’s hot! Limited supply offer!
Hmm, thanks for mentioning this, I was looking for such a tool, and now I found one.
Really nice script. Thanks.