Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

how to include header files more clearly in C++

In C++, I have some header files such as: Base.h, and some classes using Base.h:

//OtherBase1.h
#include "Base.h"
class OtherBase1{
    // something goes here
};

//OtherBase2.h
#include "Base.h"
class OtherBase2{
    // something goes here
};

And in main.cpp, I can only use one of those two OtherBase classes because of duplicate header. If I want to use both classes, in OtherBase2.h I have to #include "OtherBase1.h" instead of #include "Base.h". Sometimes, I just want to use OtherBase2.h and not OtherBase1.h, so I think it's really weird to include OtherBase1.h in OtherBase2.h. What do I do to avoid this situation and what's the best practice for including header file?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should be using include guards in Base.h.

An example:

// Base.h
#ifndef BASE_H
#define BASE_H

// Base.h contents...

#endif // BASE_H

This will prevent multiple-inclusion of Base.h, and you can use both OtherBase headers. The OtherBase headers could also use include guards.

The constants themselves can also be useful for the conditional compilation of code based on the availability of the API defined in a certain header.

Alternative: #pragma once

Note that #pragma once can be used to accomplish the same thing, without some of the problems associated with user-created #define constants, e.g. name-collisions, and the minor annoyances of occasionally typing #ifdef instead of #ifndef, or neglecting to close the condition.

#pragma once is usually available but include guards are always available. In fact you'll often see code of the form:

// Base.h
#pragma once

#ifndef BASE_H
#define BASE_H

// Base.h contents...

#endif // BASE_H

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...