Portable alternative to #pragma once

FrozenHeart picture FrozenHeart · Aug 27, 2012 · Viewed 11.3k times · Source

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?

Answer

pb2q picture pb2q · Aug 27, 2012

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.