Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Portable alternative to #pragma once

Tags:

c++

c

pragma

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?

like image 569
FrozenHeart Avatar asked Aug 27 '12 19:08

FrozenHeart


2 Answers

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.

like image 139
pb2q Avatar answered Oct 23 '22 14:10

pb2q


I like to use the traditional include guards myself (as recommended by the accepted answer). It's really not that much more work, and you get the benefit of 100% portability. If you are writing a library, posting code samples, etc, it's ideal to use that old school syntax to avoid anyone else running into trouble.

That said, it has been pointed out as well by others here that the vast majority of modern compilers respect the #pragma once directive, so it's relatively improbable you will encounter an issue using it in your own projects.

Wikipedia has a list of compilers supporting the directive:

https://en.wikipedia.org/wiki/Pragma_once#Portability

like image 34
BuvinJ Avatar answered Oct 23 '22 16:10

BuvinJ