Include guards vs pragma once

From WikiVS, the open comparison website
Jump to: navigation, search

Include guards and pragma once are both preprocessor directives that tell the compiler to only include the current file once.

Contents

[edit] Benefit

Pragma once is shorter to use and also prevents name clashes. #pragma once speed the compile time.

[edit] Problems

Pragma once might cause problems with compilers that cannot determine if a file and a symbolic or hard link are the same files. These compilers would think the file and the link are two different files, and thus compile the same code twice.

[edit] Portability

Include guards are standard C and C++ coding styles, so they are portable. Pragma once is not standard, so it is not as portable as include guards are. However, pragma once is still accepted by many compilers, including Visual Studio and GCC.

[edit] Use

Pragma once is used by calling the #pragma once directive.

File "grandfather.h"
#pragma once
 
struct foo {
    int member;
};

Include guards are used by using the standard #ifndef and #endif directives.

File "grandfather.h"
#ifndef GRANDFATHER_H
#define GRANDFATHER_H
 
struct foo {
    int member;
};
 
#endif /* GRANDFATHER_H */

See Also the Following Articles

Personal tools
Namespaces
Variants
Actions
Navigation
Ads
Toolbox