c++ - 如何避免#include 对外部库的依赖

标签 c++ dependencies static-libraries header-files

如果我正在创建一个带有如下头文件的静态库:

// Myfile.h

#include "SomeHeaderFile.h" // External library

Class MyClass
{

// My code

};

在我自己的项目中,我可以告诉编译器(在我的例子中是 Visual Studio)在哪里寻找 SomeHeaderFile.h。但是,我不希望我的用户关注这一点 - 他们应该能够包含我的 header ,而无需通知 他们的 编译器有关 SomeHeaderFile.h 的位置。

这种情况一般是怎么处理的?

最佳答案

这是一个经典的“编译防火墙”场景。有两种简单的解决方案:

  1. 从外部库中向前声明您需要的任何类或函数。然后仅在您的 cpp 文件中包含外部库的头文件(当您实际需要使用您在 header 中前向声明的类或函数时)。

  2. 使用 PImpl 惯用语(或 Cheshire Cat),您可以在其中前向声明一个“实现”类,该类您仅私下声明和定义(在 cpp 文件中)。您使用该私有(private)类来放置所有依赖于外部库的代码,以避免在您的公共(public)类(在您的头文件中声明的那个)中留下任何痕迹。

这是使用第一个选项的示例:

#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()) { };

关于c++ - 如何避免#include 对外部库的依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13978775/

相关文章:

c++ - 抽象类和多态地使用数组

maven - 如果它们来 self parent 的其他子模块,我应该依赖 Maven 中的传递依赖吗?

c++ - 项目引用和第 3 方库

c++ - 如何使用 GCC 创建基于其他静态库的静态库?

用于保存任何维数组的 C++ 变量

c++ - 如何在 C++17 中强制模板和模板参数之间的约束

c++ - boost::move 和 STL 算法

maven - "java: package org.junit does not exist"即使它在 Maven pom 中

java - 如何使用 Maven 创建一个可执行 jar 文件,其中包含主类位于 Test 中的依赖项

c++ - 为什么我的程序查找 Commons.dll 而不是 Commons.lib?