简体   繁体   中英

How to include 3rd party open source properly in c++ ?

I use several 3rd party libraries like boost, I have one class in my project, let's say it called "MyClass"

All the public functions of "MyClass" use only standard types (int,char,string), but the private functions use smart pointers from boost, and other algorithms from other libraries.

So before i write the declaration of the class (and it's functions) in the H file i write several include files.

To make the project compile i add some Additional include libraries to the project properties. And everything works fine.

The problem is that when i want to use this class from another project called USERPROJECT (the class is extern) i need to include the MyClass.h file in the USERPROJECT project, and then nothing will compile because MyClass.h includes boost and other things that are not configured in the USERPROJECT (i didn't configure the additional include libraries here, and i don't want to because he doesn't need to know them, they are in the private functions of the MyClass class).

What i the solution ?

  1. should i split MyClass to 2 class one for interface and one for implementation ?
  2. should i remove all the includes from the H and MyClass and use forward declaration ? (i tried but failed to compile it)
  3. is there a better solution

Thanks in advance

You can create compiler firewalls by using the pimpl idiom:

// header file
class C
{
public:
    ...
private:
    struct Impl;
    boost::scoped_ptr<Impl> m;
};

// cpp file
struct C::Impl
{
    // data member that were in C previously go here //
};

This way the code using your header file does not see the guts of your class. This idiom is explained in detail here . However, you can still get linking errors, if you use boost libraries that need to be linked in. If you use header-only parts of boost only, then there should be no problem.

The ideal is that every external component is accessible in every project. (And all are compiled with compatible options, etc).

If you can push toward that, your problem will be solved. And problems of other people around who wanted to use boost but faced this same impediment.

If you can't do that, you might still have solution using pimpl, but it is adds a deal of complexity, maintenance overhead and reduces readablity to some extent. And depending on what you use from boost, may only solve the compile part of the issue, as linking may require some extra lib. (unless your thing is self-contained, like a DLL)

For the latter case, if linking happens at client site, smuggling the lib is mandatory, but then it's the same amount of work to have the full boost, and avoid the chaos. So before action do some research.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM