while I am creating a c++ header file, I declare the header file like;
/*--- Pencere.h ---*/
#ifndef PENCERE_H
#define P开发者_Go百科ENCERE_H
I want to learn that why do I need to write underline.
You don't need to use the underline, it's just a convention to separate the header name and extension. You cannot use the literal .
since that's not valid in an identifier so you replace it with an underscore which is valid.
The reason you actually do it is as an include guard. The entire contents of the file are something like:
#ifndef PENCERE_H
#define PENCERE_H
// Your stuff goes here.
#endif
so that, if you accidentally include it twice:
#include "pencere.h"
#include "pencere.h"
you won't get everything in it duplicated. The double inclusions are normally more subtle than that - for example, you may include pax.h
and diablo.h
in your code and pax.h
also includes diablo.h
for its purposes:
main.c:
#include "pax.h"
#include "diablo.h"
// Other stuff
pax.h:
#ifndef PAX_H
#define PAX_H
#include "diablo.h"
// Other stuff
#endif
diablo.h:
#ifndef DIABLO_H
#define DIABLO_H
typedef int mytype;
#endif
In this case, if the include guards weren't there you would try to compile the line typedef int mytype;
twice in your program. Once for main.c -> pax.h -> diablo.h
and again for main.c -> diablo.h
.
With the include guards, the pre-processor symbol DIABLO_H
is defined when main.c
includes diablo.h
so the #define
and typedef
are not processed.
This particular mapping of header files to #define
names breaks down in the situation where you have dir1/pax.h
and dir2/pax.h
since they would both use PAX_H
. In that case, you can use a scheme like DIR1_PAX_H
and DIR2_PAX_H
to solve the problem.
The underline is not necessary, that's just a way to produce a string for the include guard that is unlikely to be produced anywhere else and cause hard to detect problems. Even more, you are free to select any symbol for the include guard as long as it will not be defined anywhere else.
It's because you can't #define PENCERE.H
You can define anything you want, but by using a format of using the filename, replacing .
with _
means you shouldn't clash #defines that guard importing the same header file twice.
You don't need to write the underline. All you need is a preprocessor symbol which isn't defined anywhere else. If you like (and/or if you have a Pascal background ;-}) you could just as well say
/*--- Pencere.h ---*/
#ifndef THE_PENCERE_HEADER_FILE_WAS_INCLUDED
#define THE_PENCERE_HEADER_FILE_WAS_INCLUDED
精彩评论