如何更清晰地包括C头文件++ [英] how to include header files more clearly in C++

查看:144
本文介绍了如何更清晰地包括C头文件++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,我有一些头文件,如:使用 Base.h ,和一些类 Base.h

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
};

而在的main.cpp ,我只能用由于重复标题的这两个 OtherBase 类之一。如果我想使用这两个类,在 OtherBase2.h 我要的#includeOtherBase1.h而不是的#includeBase.h。有时候,我只是想用 OtherBase2.h ,而不是 OtherBase1.h ,所以我认为这是很奇怪,包括 OtherBase1.h OtherBase2.h 。我该怎么做,以避免这种情况,什么是对,包括头文件中的最佳实践?

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?

推荐答案

您应该使用包括警卫 Base.h

一个例子:

// Base.h
#ifndef BASE_H
#define BASE_H

// Base.h contents...

#endif // BASE_H

这将prevent多包容 Base.h ,而你可以同时使用 OtherBase 头。在 OtherBase 头也可以使用包括警卫。

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

常数本身也可以是根据在一定的标题中定义的API的可用性code的条件编​​译有用

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.

备选: 的#pragma一次

注意的#pragma一次可用于完成同样的事情,如果没有一些与用户创建的#define 常量,如名称冲突,和偶尔打字的 #IFDEF 而不是的#ifndef ,或忽略关闭状态的小烦恼

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一次通常可用,但包括警卫始终可用。事实上,你会经常看到的形式code:

#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

这篇关于如何更清晰地包括C头文件++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆