Pragma once in cpp files

Hi! I finished the BullCow part and there is the appeared question:

#pragma once in cpp files? You added pragma once to all files in project and this confused me a little bit.

Let me explain, how i see #pragma once - according to wiki: “#pragma once serves the same purpose as include guards”, which, “include guard, sometimes called a macro guard or header guard” and it does that “The addition of #include guards to a header file is one way to make that file idempotent.”

I mean - it’s HEADER guard, so i have two questions for this lection:

  1. Why should we use #pragma once in cpp files?
  2. Why using #pragma once twice - in header and in cpp?
1 Like

Someone please correct me if I’m wrong but I don’t believe there is a use for ‘#pragma once’ in cpp files. I’ve only ever seen the directive used in header files to guard against multiple inclusion.

1 Like

You’re right, we are only adding it because it’s a common thing to see in UE code

1 Like

I agree that #pragma once is a common thing to see in UE4 header files, but not in .cpp files. In fact, if you do a solution-wide search of #pragma once appearing in .cpp files, you only get a few results, and most of them are script generators/compilers (so not a directive for the source file itself). Compare this to the thousands of header files that the directive appears in. I also googled using the directive in .cpp files and none of the results I found gave an explanation as to why you would do this - in fact all examples showed the directive being used in header files.

So, I think it’s reasonable to conclude that you don’t need to put #pragma once at the top of your .cpp files unless you have a specific reason for doing so (which should be commented to avoid confusion).

2 Likes

Privacy & Terms