ilya1725
ilya1725

Reputation: 4968

clang-format header include guard

I'd like for the clang-format to check that each of my headers have the proper include guard. For example, for the file dopelib/dopestuff/whatitisyo.h, I'd like the code to be formatted like this:

#ifndef DOPELIB_DOPESTUFF_WHATITISYO_H
#define DOPELIB_DOPESTUFF_WHATITISYO_H

/** Code here. **/

#endif  // DOPELIB_DOPESTUFF_WHATITISYO_H

Can clnag-format check this structure and make sure that the include guard is there and that it is named appropriately with the file name in the #ifndef (sort of what cpplint does)?

Upvotes: 7

Views: 4507

Answers (2)

user877329
user877329

Reputation: 6230

The accepted solution may not work if

  • The project has a different file structure
  • Uses some extensions that clang does not understand

I have a script here: https://github.com/milasudril/texpainter/blob/master/devtools/include_guard_fix.py

Upvotes: 0

Eric Backus
Eric Backus

Reputation: 1924

As far as I know, clang-format doesn't currently support this.

However, you can do exactly this with clang-tidy (documented here). Invoke it like this:

clang-tidy -checks='-*,llvm-header-guard' -fix-errors myIncludeFile.h

Explanation:

  • The -* tells clang-tidy to disable all checks
  • The llvm-header-guard tells clang-tidy to enable the check which deals with include guards (documented here)
  • The -fix-errors tells clang-tidy to fix any resulting issues, even if it runs into other errors parsing the file

The llvm-header-guard expected format of the include-guards is exactly what you requested above; for example the file mydir/myfile.h would use MYDIR_MYFILE_H. I don't see any documentation which actually specifies that this is the format it uses, but I've verified at least version 6.0.0 does use that format.

Also see: clang include fixer, which does something similar.

Upvotes: 8

Related Questions