我正在创建仅标头的C ++ 11/14库,但不确定如何处理#include
库文件之间的指令。
我应该#include
在面向用户的模块头文件中尝试将尽可能多的指令分组,还是内部文件应该包含它们所需的文件(有时重复包含相同的文件)?
方法A:
在这种方法中,模块头文件包括所有必需的依赖项,然后包括实现。实现的头文件本身不包含任何内容。
// Library/Module/Module.hpp
// This file is intended to be included by the user in his projects.
#ifndef MODULE
#define MODULE
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
#include "Library/Module/Impl/Class1.hpp"
#include "Library/Module/Impl/Class2.hpp"
#endif MODULE
--
// Library/Module/Impl/SharedDependency.hpp
#ifndef SHARED_DEPENDENCY
#define SHARED_DEPENDENCY
inline void sharedFunc() { }
#endif
--
// Library/Module/Impl/Class1.hpp
#ifndef CLASS1
#define CLASS1
// No need to include "SharedDependency.hpp", as it will be included by
// the module header file. Same applies for <vector>.
struct Class1
{
std::vector<int> v;
Class1() { sharedFunc(); }
};
#endif
--
// Library/Module/Impl/Class2.hpp
#ifndef CLASS2
#define CLASS2
// No need to include "SharedDependency.hpp", as it will be included by
// the module header file. Same applies for <vector>.
struct Class2
{
std::vector<int> v;
Class2() { sharedFunc(); }
};
#endif
方法B:
在这种方法中,模块头文件仅包含实现头。如果实现标头需要其他包含,则它们(递归地)包含文件本身,有时重复相同的包含。
// Library/Module/Module.hpp
// This file is intended to be included by the user in his projects.
#ifndef MODULE
#define MODULE
#include "Library/Module/Impl/Class1.hpp"
#include "Library/Module/Impl/Class2.hpp"
#endif MODULE
--
// Library/Module/Impl/SharedDependency.hpp
#ifndef SHARED_DEPENDENCY
#define SHARED_DEPENDENCY
inline void sharedFunc() { }
#endif
--
// Library/Module/Impl/Class1.hpp
#ifndef CLASS1
#define CLASS1
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
struct Class1
{
std::vector<int> v;
Class1() { sharedFunc(); }
};
#endif
--
// Library/Module/Impl/Class2.hpp
#ifndef CLASS2
#define CLASS2
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
struct Class2
{
std::vector<int> v;
Class2() { sharedFunc(); }
};
#endif
最好的方法是什么?
凭直觉,我认为方法A是最好的,因为它避免重复相同的包含,并弄清楚需要在其他文件之前包含哪些文件。但是,最大的缺点是语法突出显示在我的IDE(QT-Creator)中在没有包含指令的实现文件中停止工作。
编辑:
由于“基于观点”的原因,该问题被票选为关闭。我不同意,因为在一个大型的仅标头项目中,例如我的包含文件的库可能需要大量的编译时间。因此,方法A可能比方法B更快,或者相反。
方法B实际上是最好的方法,因为多次包含相同的标头不会产生任何可观察到的编译时间增加,但是由于以下原因而具有优势:
现代的IDE可以使用libclang
或专有的解决方案来解析#include
指令,并提供可识别代码的语法突出显示和自动完成功能。
如TemplateRex所述,验证合理的构建过程变得更加容易。例如,CMake提供了可为每个标头自动生成测试的宏。
正如Alf所提到的,优良作法是让每个文件都包含它依赖的所有头文件-库的用户然后可以“挑选”所需的头文件,而不是意外地强制手动包括父头文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句