how to include header files more clearly in C++

限于喜欢 提交于 2019-11-29 15:38:18

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
Sanish

You have to use header guards to avoid duplication.

http://en.wikipedia.org/wiki/Include_guard

For example in your Base.h add following:

#ifndef BASE_H_
#define BASE_H_

// stuff in Base.h

#endif

See this SO question for heard guard formats

#include header guard format?

To avoid having problems related to importing the same header file more than once, you can use the preprocessor to guard against that. The usual way of doing this is by adding these bits to Base.h:

#ifndef BASE_H_CONSTANT
#define BASE_H_CONSTANT

// Stick the actual contents of Base.h here

#endif
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!