20

In existing code I saw #pragma once be used after header #includes

//Some_Header.h
#include "header1.h"
#include "header2.h"

#pragma once

//implementations

Instead of

//Some_Header.h
#pragma once

#include "header1.h"
#include "header2.h"

//implementations

I thought it always needed to be like the second example, does it matter where your #pragma once is defined or does the preprocessor pick it up anywhere in your file?

Edit

I know #pragma once is not part of the standard and include guards are but that is not my question.

AJM
  • 1,014
  • 12
  • 23
turoni
  • 1,167
  • 1
  • 17
  • 35
  • 2
    Do keep in mind that this feature, although widely supported by various compilers, is not a part of standard C++. – Daniel Kamil Kozar Apr 19 '17 at 10:04
  • 2
    I know countless articles about this not being supported everywhere made that I couldn't really find the explanation I wanted. – turoni Apr 19 '17 at 10:05
  • 3
    I never use it, so I wouldn't know for sure - but I'd stick it as close to the beginning of the file as humanly possible. It simply makes more sense. – Daniel Kamil Kozar Apr 19 '17 at 10:06
  • 1
    I always assumed so as well, it being sort of a translation of the include guard but seeing this I wanted to be sure. – turoni Apr 19 '17 at 10:08
  • http://stackoverflow.com/questions/23696115/is-pragma-once-part-of-the-c11-standard as pragma once is not part of c++ standard.Instead of you can use following : #ifndef _DEFINED_ #define _DEFINED_ /* Your code */ #endif – Undefined Behaviour Apr 19 '17 at 10:13
  • 2
    To address the mark for duplication: The other question talks about pragma once position vs include guards. This question talks about pragma once vs header includes. So I think it is incorrectly marked. – turoni Apr 08 '19 at 08:01
  • 1
    This is not a duplicate question and thus shouldn't be marked as such. Questions are unrelated at every level. – Pablo Ariel Sep 24 '20 at 04:45

1 Answers1

24

#pragma once should be placed before any headers are included. Argument of #pragma directive is a subject to macro expansion. So content of included headers can alter the pragma behavior:

// whatever.hpp
...
#define once lol_no

// your_header.hpp
#include "whatever.hpp"

#pragma once // warning C4068: unknown pragma
user7860670
  • 33,577
  • 4
  • 51
  • 80