1

1.I see that many places, Header guards and pragma once are used together that too in a specific order(does the order actually matter?)

2.Also another doubt is by default whenever a new class file is generated by VS IDE it puts #pragma once to the implementation file(.cpp). Is this really required?

#ifndef MYHEADER_H
#define MYHEADER_H

#pragma once

//my set of includes

Which is the right way of header guards or rather blocking multiple inclusions?

JBL
  • 12,588
  • 4
  • 53
  • 84
surega
  • 707
  • 7
  • 15
  • To gain the benefits of it, if there still is any (@jalf), I'd imagine you'd have to have it first. – ChiefTwoPencils Feb 15 '13 at 21:38
  • See also [Why isn't C/C++'s "#pragma once" an ISO standard?](http://stackoverflow.com/questions/1695807/why-isnt-c-cs-pragma-once-an-iso-standard?rq=1) – Bo Persson Feb 15 '13 at 21:43

2 Answers2

3
#pragma once  

Is non-standard, although supported by many popular compilers / pre-processors. See Is #pragma once a safe include guard?

#ifndef MYHEADER_H
#define MYHEADER_H
#endif // ndef MYHEADER_H

Is guaranteed to work with all C++ compilers / pre-processors.

There is no point in using both at the same time.

Community
  • 1
  • 1
johnsyweb
  • 136,902
  • 23
  • 188
  • 247
0

"#pragma once" is compiler specific and potentially not portable. "#ifndef/#define/#endif" is more portable and will work for all preprocessors.

Markus Schumann
  • 7,636
  • 1
  • 21
  • 27
  • So does that mean its a good practise to add both? I couldnt reason why both are used in the code? Does it give any additional compilation optimisations if #pragma is also seen or compiler optimisation will as well do away with #defines? – surega Feb 15 '13 at 21:35
  • I do #pragma once and include guards. I never compared performance of #pragma once vs include guards but I could imagine that aborting parsing after #pragma once is faster than looking for #endif. – Markus Schumann Feb 18 '13 at 18:27