0

I have A.cpp and B.cpp which both include the header file header.h.

Later both A.cpp and B.cpp are included in a main.cpp.

This causes error when main.cpp is compiled saying that the header file header.h has been included twice.

How to solve this ?

Chani
  • 5,055
  • 15
  • 57
  • 92

3 Answers3

4

You should surround your header files in

#ifndef MYFILE_H
#define MYFILE_H

// Contents of your file

#endif

These are called include guards.

Second point: you shouldn't be including .cpp files, only .h files.

alestanis
  • 21,519
  • 4
  • 48
  • 67
  • The header files are from a library. So I cannot add header guards there. What must i do now ? – Chani Feb 23 '13 at 20:41
  • Header files not mandatory have .h extentions, so please change your suggestion, it can confuse some novice programers. – Slava Feb 23 '13 at 20:42
  • 1
    @RitwikG That sounds like the "library" is thorougly broken. My advice: drop that piece of crap and use something that can actually be called a library. – R. Martinho Fernandes Feb 23 '13 at 20:44
2

Use include guards. in your headers, for example:

// Header.h
#ifndef HEADER_H_
#define HEADER_H_

// code from original header.h

#endif

And don't include .cpp files in other .cpp files. Include the necessary headers only.

Edit If the header files come from a 3rd party library, and do not have include guards, I would be very suspect of that library. I would drop it. However, you can make your own headers, including the library header in an include guard:

// FixedHeader.h
#ifndef HEADER_H_
#define HEADER_H_

#include "header.h"

#endif

Then #include "FixedHeader.h". But I would drop the library, seriously.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • The header files are from a library. So I cannot add header guards there. What must i do now ? – Chani Feb 23 '13 at 20:40
  • @RitwikG if they are from a library, they should already have include guards. If they don't, then drop the library, it is no good! Although note that, on Windows at least, include guards can be expressed with `#pragma once` or something like that. – juanchopanza Feb 23 '13 at 20:41
2

If you cannot modify header file to include guards, there are 3 possible solutions (sorted from the best to worse):

1 Do not use that garbage.
2 Use wrapper my_header.h

#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <header.h>
#endif // MY_HEADER_H

include my_header.h instead of header.h in your code

3 Use guards in .cpp file

 #ifndef HEADER_H  
 #define HEADER_H  
 #include <header.h>  
 #endif // HEADER_H

you have to be consistent though and use the same guards everywhere (that's why it is solution 3)

Slava
  • 43,454
  • 1
  • 47
  • 90