Portable alternative to #pragma once

#pragma once is a non-standard alternative to include guards:

#ifndef HEADER_H
#define HEADER_H

//contents of header

#endif

Both ensure the header content is not pasted more than once in the same translation unit.


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


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.

Tags:

C++

C

Pragma