Reputation: 48916
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.
Upvotes: 1
Views: 4074
Reputation: 5300
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.
Upvotes: 6
Reputation: 15289
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.
Upvotes: 2
Reputation: 13628
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
Upvotes: 4