Astyle: Formatting Source Code On The Command Line
April 25, 2011 Leave a Comment
As promised, here is a tutorial. This one is quick.
Most programmers use an Integrated Development Environment (IDE) for their programming projects. IDEs are very convenient as they provide intellisense, formatting options, spell check, etc. For me, I still use vim and gedit for my coding.
What I really want from the IDE is the auto formatting feature. It really sucks that after writing 300 lines of code, you find out that you need an if statement in the middle and that statement wraps around a good 140 lines of your code. Now for languages such as C++ and Java, formatting does not matter when it comes to compiling and executing programs. However, formatting does matter to the programmer. Without proper formatting, we will go crazy just trying to figure out where the indentation begins and where all the curly braces are located.
You can dedicate a few hours just to format everything, but why bother wasting your life when you can just use a formatting program? One program that can do so is astyle.
How to use astyle…
First you have to download astyle. On Debian based systems, just use apt-get:
apt-get install astyle
Here is the format:
astyle [OPTIONS] file_name.
Suppose I have a source code called uglyProgram.c. In it contains the following:
#include //stdio.h
#include //stdlib.h
int main(int argc, char *argv[]){
int uglyNumber = 16;
char *horribleINdedation = "dsfljksdlfssd";
int counter = 0;
for (; counter < uglyNumber; counter++){
printf("Do something...\n");
}
exit(0);
}
Horrible formatting. Let us fix that with astyle:
astyle uglyProgram.c
Now when you open up uglyProgram.c, you will get this:
#include //stdio.h
#include //stdlib.h
int main(int argc, char *argv[]) {
int uglyNumber = 16;
char *horribleINdedation = "dsfljksdlfssd";
int counter = 0;
for (; counter < uglyNumber; counter++) {
printf("Do something...\n");
}
exit(0);
}
Much better! Note that astyle can format multiple source codes at the same time like so:
astyle code1.c code2.c code3.c
or
astyle *.c