How to fix header guards using guardonce

Header guards are used in C and C++ header files to avoid them being included more than once during the compilation of a compilation unit. There are generally two techniques: using an include guard and using a pragma once directive. guardonce provides a set of Python tools that can be used to diagnose the state of header guards, convert between the two types of guards and to fix guards in your codebase.

  • Installing guardonce using pip is easy:
$ sudo pip3 install guardonce
  • To convert include guards to pragma onces for all header files in the current directory:
$ guard2once *.h
  • To convert pragma onces to include guards for all header files in the current directory:
$ once2guard *.h
  • The tools support a pattern language that can be used to specify include guard name of a specific pattern. The pattern is built like a Unix pipeline. For example, to convert pragma once to include guard names with a default prefix (say FOOBAR_) followed by filename in snake form and uppercase:
$ once2guard -p "name | snake | upper | prepend FOOBAR_" *.h

For a filename linkedList.h the above command would generate an include guard name FOOBAR_LINKED_LIST_H.

  • For include guards it is convenient to have the guard name to appear in comments near the endif. To do that:
$ once2guard -s "#endif // %" *.h
  • It is a good convenience to have a newline before the endif. To do that:
$ once2guard -l *.h
  • There is no straightforward option to fix or modify the include guards to a certain pattern. Instead I found that I could achieve this by first converting the file to pragma once and then converting back to include guards. This can be done like this:
$ guard2once *.h ; once2guard *.h

Tried with: guardonce 2.4.0 and Ubuntu 18.04

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.