Search code examples
c++pragma

#pragma once position: before or after #include's


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.


Solution

  • #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