Possible Duplicate:
#pragma once vs include guards?
When should I use #pragma once
?
When should I use #ifndef HEADER_H_INCLUDED
?
The #ifndef/#define/#endif trick works on any C compiler, and on some of them it speeds up the compilation process. The #pragma trick is non-standards, and only works on few C compilers, and may result in different semantics in those that do not support it.
The difference is that the latter is C and the former is not. Never use #pragma once
; always use #ifndef
.
One other thing to note when using the #ifndef
method is that any preprocessor symbol beginning with two underscores or an underscore followed by a capital letter is reserved and cannot be used. You should use things like #ifndef MYHEADER_H
and not #ifndef _MYHEADER_H
.
The construct
myfoo.h
#ifndef MYFOO_H
#define MYFOO_H
/* header information for myfoo.h */
#endif
belongs in every header-file. The trick is: you can include a header file (accidentally) more than once without thinking abaout double declarations. so this is for the preprocessor.
The #pragma is for the compiler, and a preprocessor should ignore pragmas it does not understand.
Use #pragma
when you are addressing a specific compiler (or set of compatible compilers) to guide its code generation or if you are using a standardized #pragma
like FP_CONTRACT
or -CX_LIMITED_RANGE-
that any standards-compliant compiler is going to support.
Use #ifndef
and ilk if you are addressing the standard C (or C++) pre-processor and wish to have your code rendered portable across all standards-compliant compilers.
Use of any #pragma
that is not defined in the C (or C++) standard renders your code non-portable. #pragma once
is a bit of an exception in that it is one of the most commonly-implemented of the non-standard #pragma
constructs. Its implementation, however, is not universal across standards-compliant compilers. #ifndef
is.
精彩评论