Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide contents of third-party C++ header file

I'm creating a static library in C++ to define a class that others can use in their code. However, a member of the class is of a type defined in a header file obtained from someone else, and I don't want to distribute the contents of this person's header file.

Here is the current public interface (interface.h):

class B {
    TypeToHide t;
    // other stuff ...  
};

class A {
    double foo();
    B b;
};

And here is the code that will be compiled into a static library (code.cpp):

double A::foo() {
    // ...
}

And here is the file whose contents I need to hide from public view (HideMe.h):

struct TypeToHide {
    // stuff to hide
};

What can I do hide the contents of HideMe.h? Ideally, I could just stick the entire struct from HideMe.h into code.cpp.

like image 534
synaptik Avatar asked Dec 16 '12 16:12

synaptik


People also ask

How do you prevent multiple inclusions of header files?

To avoid multiple inclusions of the same header file we use the #ifndef, #define and #endif preprocessor directives. Just write the entire program in only file and include headers once only.

How do I put a header only on libraries?

Header-only libraries do not need to be separately compiled, packaged and installed in order to be used. All that is required is to point the compiler at the location of the headers, and then #include the header files into the application source.

Which header file automatically Inclueds in source code?

In computer programming, a precompiled header (PCH) is a (C or C++) header file that is compiled into an intermediate form that is faster to process for the compiler.


2 Answers

You can use the PIMPL idiom (Chesshire Cat, Opaque Pointer, whatever you want to call it).

As the code is now, you can't hide the definition of TypeToHide. The alternative is this:

//publicHeader.h
class BImpl;          //forward declaration of BImpl - definition not required
class B {
    BImpl* pImpl;     //ergo the name
    //wrappers for BImpl methods
};

//privateHeader.h
class BImpl
{
    TypeToHide t;  //safe here, header is private
    //all your actual logic is here
};
like image 64
Luchian Grigore Avatar answered Sep 22 '22 17:09

Luchian Grigore


Simpler than Pimpl, you can use a pointer to TypeToHide and a forward declaration for it:

class B {
    TypeToHide* t;
    // other stuff ...  
};

As long as you won't need knowledge about t's internal structure for the user's code, you won't have to expose it and it will stay safe in your library.
The code inside the library will have to know what TypeToHide is, but that's not a problem.

like image 41
Oren S Avatar answered Sep 19 '22 17:09

Oren S