954,496 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ Preprocessor

#ifndef Test_h
#define Test_h
#endif


May I know what are the above 3 syntax for? How can I use it?
Is is used only in header file?

makan007
Junior Poster in Training
70 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

It's a guard against including the information in the header file more than once(which can cause a mess with redeclarations etc.).
You'd put the contents of your header between lines 2 and 3. At first pass if this symbol Test_h is not defined, processing goes to line 2 which defines Test_h and then continues with the rest of the header until the endif.
If you include this file again somewhere and that symbol is found to be already defined the preprocessor hits line 1 and skips to line 3 since the ifndef is false.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

I can just use this right?

#include <iostream>
using namespace std;
makan007
Junior Poster in Training
70 posts since Jan 2010
Reputation Points: 10
Solved Threads: 0
 

It's almost apples and oranges but not quite. Say you have a class A and you put the declaration for that class into it's own header file,one that you wrote. Say that your class B header file, B.h, includes A's header, A.h. If you then include A.h and B.h in main.cpp you will have 2 copies of A.h being included. Your guard prevents this and it's only included once. It doesn't seem like a complicated situation but with a large project there can be crossovers all over the place.

In the case of the headers that we normally include for library files (like iostream) they have their own guards in place to prevent this.

#ifndef _GLIBCXX_IOSTREAM
#define _GLIBCXX_IOSTREAM 1

#pragma GCC system_header

is in the header. I'm not sure if this particular pragma is involved in that whole process or not.

If you work with Visual Studio (and possibly other compilers) they also use the #pragma once directive to accomplish the same task.

jonsca
Quantitative Phrenologist
Team Colleague
5,621 posts since Sep 2009
Reputation Points: 1,165
Solved Threads: 581
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You