Search code examples
c++cpragma

Portable alternative to #pragma once


Can somebody tell me a workaround for #pragma once directive support for various compilers?

I want to use in my header something like:

#if _MSC_VER > ... || __GNUC__ > ... || ...

#pragma once

#endif

Maybe it already exists in boost sources or in your code?


Solution

  • Use include guards:

    #ifndef MY_HEADER_H
    #define MY_HEADER_H
    
    // ...
    
    #endif    // MY_HEADER_H
    

    Sometimes you'll see these combined with the use of #pragma once:

    #pragma once
    
    #ifndef MY_HEADER_H
    #define MY_HEADER_H
    
    // ...
    
    #endif    // MY_HEADER_H
    

    #pragma once is pretty widely supported.