Can I use a slim version of my header to be included with the library?

Viewed 157

What I mean is my real header file can look like this:

#include "some_internal_class.h"

class MyLibrary {
    Type private_member;

    void private_function();
public:

    MyLibrary();
    void function_to_be_called_by_library_users();
};

Now I want to produce a dynamic library containing all the necessary definitions. and I want to ship with it a single header instead of shipping every single header I have in my library.

So I was thinking I could create a slim version of my header like so:

class MyLibrary {
public:     
    MyLibrary();
    void function_to_be_called_by_library_users();
};

Headers are just declarations anyway right? they're never passed to the compiler. And I've declared what the user will be using.

Is that possible? If not, why not?

4 Answers

Headers are just declarations anyway right? they're never passed to the compiler.

The moment you do a #include to a file, its content are copied and pasted into your source file exactly as they are. So even though you don't pass them directly as compiler arguments, they're still part of your code and code in them will be compiled into your translation units.

Solutions by @lisyarus are pretty good.

But another option would be doing it the C way. Which is the most elegant in my opinion.

In C you give your users a handle, which will most likely be a pointer.

Your header would look something like this:

struct MyLibrary;

MyLibrary*
my_library_init();

void
my_library_destroy(MyLibrary*);

void
my_library_function_to_be_called_by_library_users(MyLibrary*);

A very small and simple interface that does not show your users anything you don't want them to see.

Another nice perk is that your build system will not have to recompile your whole program just because you added a field to the MyLibrary struct.

You have to watch out though, because now you have to call my_library_destroy which will carry the logic of your destructor.

Related