读书人

#ifndef X.endif中如果包含X两次是否会

发布时间: 2013-07-04 11:45:28 作者: rapoo

#ifndef X....#endif中如果包含X两次是否会导错误,什么样的错误啊。
看书的时候说如果#ifndef X....#endif中包含X两次会直接跳到#endif后面,那么是否程序还能运行,但是有一些结构声明,函数原型之类的没有了,导致一些错误。或是别的什么错误呢?求教了。


Header File Management
You should include a header file just once in a file. That might seem to be an easy thing to
remember, but it’s possible to include a header file several times without knowing you did
so. For example, you might use a header file that includes another header file. There’s a
standard C/C++ technique for avoiding multiple inclusions of header files. It’s based on the
preprocessor #ifndef (for if not defined) directive. A code segment like the following
means “process the statements between the #ifndef and #endif only if the name
COORDIN_H_ has not been defined previously by the preprocessor #define directive”:
#ifndef COORDIN_H_
...
#endif
Normally, you use the #define statement to create symbolic constants, as in the following:
#define MAXIMUM 4096
But simply using #define with a name is enough to establish that a name is defined, as in
the following:
#define COORDIN_H_
The technique that Listing 9.1 uses is to wrap the file contents in an #ifndef:
#ifndef COORDIN_H_
#define COORDIN_H_
// place include file contents here
#endif
The first time the compiler encounters the file, the name COORDIN_H_ should be undefined.
(I chose a name based on the include filename, with a few underscore characters tossed
in to create a name that is unlikely to be defined elsewhere.) That being the case, the compiler
looks at the material between the #ifndef and the #endif, which is what you want.
In the process of looking at the material, the compiler reads the line defining COORDIN_H_.
If it then encounters a second inclusion of coordin.h in the same file, the compiler notes


that COORDIN_H_ is defined and skips to the line following the #endif. Note that this
method doesn’t keep the compiler from including a file twice. Instead, it makes the compiler
ignore the contents of all but the first inclusion. Most of the standard C and C++ header
files use this guarding scheme. Otherwise you might get the same structure defined twice in
one file, and that will produce a compile error.

读书人网 >C++

热点推荐