1

At: http://www.learncpp.com/cpp-tutorial/110-a-first-look-at-the-preprocessor/

Under Header guards, there are those code snippets:

add.h:

#include "mymath.h"
int add(int x, int y);

subtract.h:

#include "mymath.h"
int subtract(int x, int y);

main.cpp:

#include "add.h"
#include "subtract.h"

How can I avoid #include "mymath.h" from appearing twice in main.cpp?

Thanks.

Simplicity
  • 47,404
  • 98
  • 256
  • 385
  • Why do you want to avoid it being included twice? – sth Jan 22 '11 at 17:24
  • 2
    The point of include guards isn't to stop the preprocessor from seeing the same `#include` more than once, it's to stop the actual code in mymath.h from being included twice. Assuming you have include guards in mymath.h, you're fine. – John Flatness Jan 22 '11 at 17:26
  • 6
    The answer is actually in the next paragraph in that tutorial. Why are you asking that question here? – Björn Pollex Jan 22 '11 at 17:26

4 Answers4

6

The lines right below that example explain it. Your mymath.h file should look like this:

#ifndef MYMATH_H
#define MYMATH_H

// your declarations here

#endif

Every header file should follow this basic format. This allows a header file to be included by any file that needs it (both header and source files), but the actual declarations will only be included at most once in each source file.

JaredC
  • 5,150
  • 1
  • 20
  • 45
4

use #pragma once if you using MS VC++ or the standard way

inside mymath.h

#ifndef MYMATH_H
#define MYMATH_H

[code here]

#endif // MYMATH_H
Andrew T Finnell
  • 13,417
  • 3
  • 33
  • 49
2

That's ok if they included twice if all the headers files have header guards. The second and all subsequent inclusions would just add empty lines and there won't be any code duplication. Just make sure that mymath.h has header guards as well.

detunized
  • 15,059
  • 3
  • 48
  • 64
1

You should put your header guards in any header, also in mymath.h.

peoro
  • 25,562
  • 20
  • 98
  • 150