2

Based on other answers on SO such as #pragma once vs include guards? as well as what I've seen in some open source and other projects, #pragma once seems to be standard practice. Yet, the CPP Core Guidelines here recommend against it(the note seems pretty strong against #pragma once).

As long as I'm an up-to date compiler do I need to worry about this? In which situations, should I be wary of using them?

Edit:
If someone could also clarify what the following means:
It injects the hosting machine's filesystem semantics into your program

This answer seems to thoroughly provide an answer to this question.

tangy
  • 2,330
  • 1
  • 16
  • 34
  • 1
    The CCG are very clear why they make this recommendation. Feel free to disagree, but do not ask **why** when the answer was given. Your mentioning C++11 makes no sense, it is not relevant to `#pragma once` in any way. – SergeyA Nov 29 '18 at 22:40
  • 1
    `#pragma once` is **not** part of standard C++. Some compilers support it, but it has technical flaws; it can fail in networked environments where the same file can come in through different paths. – Pete Becker Nov 29 '18 at 22:41
  • 1
    The core guidelines gives you the best reason I know *Some implementations offer vendor extensions like #pragma once as alternative to include guards. It is not standard and it is not portable. It injects the hosting machine's filesystem semantics into your program, in addition to locking you down to a vendor.*. Translation: **Portability** – NathanOliver Nov 29 '18 at 22:42
  • @SergeyA agreed - I have edited my question accordingly. – tangy Nov 29 '18 at 22:42
  • Note that you have no obligation to follow Cpp Core Guidelines, it's just another style guide – M.M Nov 29 '18 at 22:51
  • But I don't think that answer mentions the situations where it should be avoided with upto date compilers - eg. Like @PeteBecker mentioned "but it has technical flaws; it can fail in networked environments where the same file can come in through different paths." In fact I was hoping he could elaborate? – tangy Nov 29 '18 at 22:52
  • 1
    @tangy the duplicate has an answer titled "#pragma once has unfixable bugs. It should never be used" which talks about exactly those issues. – SergeyA Nov 29 '18 at 23:01
  • 1
    I think `#pragma once` may resolve differently or even fail where there are multiple paths because of things like *symbolic links* or *virtual paths* – Galik Nov 29 '18 at 23:03
  • 1
    @tangy say you have a header `foo.h` and it's a symbolic link to `bar.h`. Then including both means the guard with pragma will fail. – Matthieu Brucher Nov 29 '18 at 23:03
  • Yes @SergeyA , this answer https://stackoverflow.com/a/34884735/3656081 from the linked question does seem to answer my question. – tangy Nov 29 '18 at 23:05
  • 1
    See the answer by zwol in the duplicate. – Pete Becker Nov 29 '18 at 23:05

0 Answers0