including header file more than once

Hi,

When I am including header file (#include <stdio.h> ) 2 time in a same file, am not getting any error but if I am including my own file(add.h) including (#include <add.h>) 2 time in a same file a getting following error

variables are already declared

can anyone please explain why?
HI Disch,

I did not get exact point from that. Please tell me why am I getting?
The problem belongs to memory or any other one?

Please help me...
It belongs to #include copying and pasting in the contents of the file multiple times, causing the compiler to see all the variables and such multiple times.The article explains all of this, though...
so why we are not getting for #include <stdio.h>?
stdio.h has header guards like the article suggests.
Because stdio.h is guarded.

EDIT:

To elaborate (and by "elaborate"... I mean copy/paste sections of that link here):

1
2
3
4
5
6
 // myclass.h

class MyClass
{
  void DoSomething() { }
};

1
2
3
4
5
 
 // main.cpp
#include "myclass.h"   // define MyClass
#include "myclass.h"   // Compiler error - MyClass already defined
 


An Include Guard is a technique which uses a unique identifier that you #define at the top of the file. Here's an example:


1
2
3
4
5
6
7
8
//x.h

#ifndef __X_H_INCLUDED__   // if x.h hasn't been included yet...
#define __X_H_INCLUDED__   //   #define this so the compiler knows it has been included

class X { };

#endif  


This works by skipping over the entire header if it was already included. __X_H_INCLUDED__ is #defined the first time x.h is included -- and if x.h is included a second time, the compiler will skip over the header because the #ifndef check will fail.

Always guard your headers. Always always always. It doesn't hurt anything to do it, and it will save you some headaches. For the rest of this article, it is assumed all header files are include guarded (even if I don't explicitly put it in the example).
Last edited on
Topic archived. No new replies allowed.