如何避免#crude依赖外部库
How to avoid #include dependency to external library
如果我使用以下标题文件创建静态库:
// Myfile.h
#include "SomeHeaderFile.h" // External library
Class MyClass
{
// My code
};
在我自己的项目中,我可以告诉编译器(在我的情况下,Visual Studio)在哪里寻找SomeheaderFile.H。但是,我不希望我的用户关心这一点 - 他们应该能够包含我的标题,而不必通知他们的编译器有关Someheaderfile.H。H。
的位置。这种情况通常如何处理?
这是经典的"编译防火墙"方案。有两个简单的解决方案要做:
-
向前销售您需要从外部库中需要的任何类或功能。然后仅在CPP文件中包含外部库的标头文件(当您实际需要使用您在标题中转发的类或功能时)。
-
使用PIMPL IDIOM(或Cheshire Cat),您可以将您声明并仅私下定义(在CPP文件中)转发为"实现"类。您使用该私有类将所有与外图的代码放置在公共类中避免具有任何痕迹(在标题文件中声明的痕迹)。
这是使用第一个选项的示例:
#ifndef MY_LIB_MY_HEADER_H
#define MY_LIB_MY_HEADER_H
class some_external_class; // forward-declare external dependency.
class my_class {
public:
// ...
void someFunction(some_external_class& aRef); // declare members using the forward-declared incomplete type.
};
#endif
// in the cpp file:
#include "my_header.h"
#include "some_external_header.h"
void my_class::someFunction(some_external_class& aRef) {
// here, you can use all that you want from some_external_class.
};
这是选项2的示例:
#ifndef MY_LIB_MY_HEADER_H
#define MY_LIB_MY_HEADER_H
class my_class_impl; // forward-declare private "implementation" class.
class my_class {
private:
std::unique_ptr<my_class_impl> pimpl; // a vanishing facade...
public:
// ...
};
#endif
// in the cpp file:
#include "my_header.h"
#include "some_external_header.h"
class my_class_impl {
private:
some_external_class obj;
// ...
public:
// some functions ...
};
my_class::my_class() : pimpl(new my_class_impl()) { };
说外部标头文件包含以下内容:
外部.h
class foo
{
public:
foo();
};
在您的库中,您使用foo:
myheader.h:
#include "external.h"
class bar
{
...
private:
foo* _x;
};
要使您的代码编译,您所要做的就是转发声明foo类(之后您可以删除包含):
class foo;
class bar
{
...
private:
foo* _x;
};
您必须在源文件中包含external.h。
相关文章:
- 使用 Git 处理 C++ Visual Studio 2019 解决方案的外部依赖项源代码管理的最佳方法是什么?
- 如何将外部依赖引入跨平台CMake项目?
- 当 lib 已添加到其他依赖项时,如何在 VS 中调试未解析的外部符号错误
- 使用 cmake 获取外部依赖关系
- CMake 外部和内部静态库的循环依赖关系
- 如何在bazel中同时处理外部依赖项和我的项目
- 如果 copts 不允许系统路径,如何引用外部依赖项使用的系统库?
- 使用外部依赖项运行 VC++ 单元测试时"Failed to set up execution context"
- 无法构建外部库依赖项
- 如何忽略来自 Bazel 中的外部C++依赖项标头的警告
- CMake 和外部依赖关系
- 使用 CMake 外部项目为跨平台库依赖项的目标名称
- 是否可以编译具有在编译时无法解析的外部依赖项的静态库?
- C++项目文件夹外部依赖项仅包含 .h 和 .hpp 文件
- 如何避免#crude依赖外部库
- 在Visual Studios 2010的外部依赖项文件夹中搜索文本/代码
- visualstudioc++的外部依赖关系
- 如何从需要外部依赖关系的多个.o文件中创建可执行文件
- 在.lib项目中包含外部依赖项
- BDS 2006构建无外部依赖的可执行文件