Jun's Blog

Output, activities, memo and etc.

Formatting the C code by GNU indent.

If you read the source code of C language or develop in it, you may do formatting the code by your favorite indent style.

I like K&R indent style, and 4 spaces as a indent, personally.

For this purpose, the tool "GNU indent" is useful.

In this case, I will install it on Mac.

Take note the following default installed indent is not GNU indent.
I do not use this.

$ which indent
/usr/bin/indent

Install

$ brew install gnu-indent

How to use

Options:

  • -kr: K&R style.
  • -nut: No tabs. Use spaces instead of tabs. This option is for indent: 4 spaces.

Argument files are converted by specified indent style.

$ gindent -kr -nut {c or header file}

If you want to use this for all the .c or .h files, type as following.

$ find . -name "*.c" -o -name "*.h" | xargs gindent -kr -nut

It is useful to use this in Makefile.

$ vi Makefile
...
format:
    find . -name "*.c" -o -name "*.h" | xargs gindent -kr -nut
.PHONY : format
...

That's all.