0

i created a class in visual studio c++ and realized that it added a single '#pragma once' to the start of the header file, what is the difference between #pragma once and header guards that use preprocessor conditionals?

i am guessing that it is used as a replacement for header guards but i am not sure how does #pragma once work or does it create any differences in performance,portability,etc... also i don't know which one is better to use in header files

// what i get when i use the visual studio c++ class wizard
#pragma once
// what i was taught in class
#ifndef HEADER_FILE
#define HEADER_FILE
//some code
#endif //HEADER_FILE
  • *but i am not sure how does #pragma once work* -- Maybe it doesn't do anything for the compiler toolset you are using. What you were taught in class is the way it works universally, for any compiler brand. – PaulMcKenzie Mar 25 '22 at 15:04
  • 1
    Unless you use an ancient compiler, pragmas are fine – Alexey Larionov Mar 25 '22 at 15:07
  • Always check your compiler's documentation before going the `pragma` route. – ChrisMM Mar 25 '22 at 15:27
  • `#pragma once` is a great way to introduce build bugs. (It never seems to handle files with the same name in different directories.) It might work on your current compilers, but then f**** up when you need to target another architecture. By the way, I always use `#define HEADER_FILE 1` . You don't need to by the C++ standard but it can help if you ever need to refer to an include guard. – Bathsheba Mar 25 '22 at 15:34
  • My recommendation is to use `#pragma once`. They are safer to me, as it is too easy to use erroneously two `#define` guard names that are identical. Especially when copy-pasting a header and forgot to change that name. It can get unnoticed for a long time before you have strange build errors. In happened to our company a few times, before we switched to `#pragma once` everywhere. – prapin Mar 25 '22 at 15:56
  • @prapin: When I'm hired we'll switch them back ;-) – Bathsheba Mar 25 '22 at 16:19
  • `#pragma once` is not standard and, despite the upbeat comments, there are situations where it does not (and cannot) work correctly. – Pete Becker Mar 25 '22 at 19:38
  • `#pragma once` -- "I hope the compiler figures this out". Compare that to `"#ifndef ABC_H #define ABC_H #endif` -- "I know what this does, and works every time". I take the latter. – PaulMcKenzie Mar 25 '22 at 20:29

0 Answers0