How to avoid #include dependency to external library

送分小仙女□ 提交于 2019-12-02 20:47:05

This is a classic "compilation firewall" scenario. There are two simple solutions to do:

  1. Forward-declare any classes or functions that you need from the external library. And then include the external library's header file only within your cpp file (when you actually need to use the classes or functions that you forward-declared in your header).

  2. Use the PImpl idiom (or Cheshire Cat) where you forward-declare an "implementation" class that you declare and define only privately (in the cpp file). You use that private class to put all the external-library-dependent code to avoid having any traces of it in your public class (the one declared in your header file).

Here is an example using the first option:

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

Here is an example of option 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()) { };

Say the external header file contains the following:

external.h

class foo
{
public:
   foo();
};

And in your library you use foo:

myheader.h:

#include "external.h"

class bar
{
...
private:
   foo* _x;
};

To get your code to compile, all you have to do is to forward declare the foo class (after that you can remove the include):

class foo;

class bar
{
...
private:
   foo* _x;
};

You would then have to include external.h in your source file.

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