Balázs Árva
Balázs Árva

Reputation: 256

Automatically add #pragma once to header files

I try to remove every unnecessary boilerplate code from my personal projects. The first thing, I have noticed, is first line of every header files #pragma once. Not so surprising. However, I would like to ask my compiler (clang SVN HEAD version) to automatically add this line to my header files (for example with a pattern like this: src/*.hpp). I think there are very rare cases when you actually want to include one header multiple times.

  1. Do you agree?
  2. Is there any existing solution for this problem?
  3. Do you think this is a good idea?

With clang tools this issue can be solved, but I need some little help to start this extension.

  1. Which clang tool should I use?

Theoretical usage of this tool/extension:

clang --auto-pragma-once src/*.hpp src/*.cpp -o test

Thank you for any advice

EDIT:

  1. I do not want to store this pragma once in my file. So any editor or any other tools which place new things in the files are not working for this problem.

  2. This topic is about the one-time inclusion of header files, not the pragma once.

Upvotes: 1

Views: 2320

Answers (2)

James Kanze
James Kanze

Reputation: 154007

I'm not sure why you'd want to use clang for this. It depends on the editor, but every editor I know allows you to trigger on things like opening a new file whose name matches a specific pattern, and insert boilerplate in it. In industry, it's pretty much forbidden not to use this, since that's how the copyright notices get inserted. In my case, for example, if I create a new file with the name xyz.hh, the editor comes up with

/****************************************************************************/
/*      File:       xyz.hh                                                  */
/*      Author:     J. Kanze                                                */
/*      Date:       25/09/2013                                              */
/*      Copyright ....                                                      */
/* ------------------------------------------------------------------------ */

#ifndef xyz_hh_20130925QPIvFK6xMJYLBhSpv58ROPOU
#define xyz_hh_20130925QPIvFK6xMJYLBhSpv58ROPOU

#endif
//  Local Variables:                        --- for emacs
//  mode: c++                               --- for emacs
//  tab-width: 8                            --- for emacs
//  End:                                    --- for emacs
//  vim: set ts=8 sw=4 et filetype=cpp:     --- for vim  

If I do this in my work domain, the copyright notice is different, the include guards follow a different standard, and there's also a #pragma once.

Upvotes: 0

Neil Kirk
Neil Kirk

Reputation: 21803

Just bite the bullet and put the pragma in your header files. It's only one line and if there is nothing, it might confuse others who look at your files.

Upvotes: 2

Related Questions