Monday, June 8, 2009

Including a Header Files Only Once.................



To prevent multiple copy of header file, a header file can be
written to detect whether it has already been included. The
following is an example of how this can be done:
/* header.h */
#ifndef HEADER_H
#define HEADER_H
/* The body of the header file */
#endif /* HEADER_H */
In this example, the header file is named header.h. The first
line tests whether HEADER_H has been defined. If it has, the
entire header file is skipped. If HEADER_H has not been defi-
ned, it is immediately defined and the header file is proces-
sed. The system header files all use this technique. The names
defined in them all begin with an underscore character to
prevent them from interfering with any names you define. The
convention is for the defined name to be in all uppercase and
to contain the name of the file.


Example:
=============================================================
/*test.h*/

#ifndef _TEST_H /*if not defined */
#define _TEST_H /*then define */

class test
{
private:
int data;
public:
test();
void functionOne();

};

test::test()
{
cout < < "i got nothing to do here" <
< endl;
}

void test::functionOne()
{
cout < < " I m in function One" < <
endl;
}
#endif /*End of definition */
____________________________________________________________

/* main.cpp */

#include "test.h"
#include "test.h"
#include "test.h"

#include < iostream >

using namespace std;


int main()
{
test obj;
obj.functionOne();
return 0;
}
=============================================================

Now you can see the work of only preprosessor by using the
compilation option:
g++ -E main.cpp < output.txt

Now an output file "output.txt" will be created which
contains all the source code after the work of preprocessor
has been done. At the begining it can be seen that the test.h
is defined only once. then after this iostream is defined and
at last source code of main.cpp




No comments:

Post a Comment

Search Ranjeet's Blog