jpen
jpen

Reputation: 2147

C++ - Proper way to export public parts of C++ library

I have the following files in my ./mylib/src directory. I want anything in this location to be hidden from user.

message.h file (in ./mylib/src)

// Include guard
namespace MyLib
{
    class Message
    {
    public:
        Message();
        virtual ~Message() = 0;

        virtual bool ToString(std::string& rstrOutput);
        bool IsEmpty() const;

    protected:
        void DoStuff();

    private:
        Message(const Message&); // Disable
        Message& operator=(const Message&); // Disable

    private:
        int m_nData;
    };
}

request.h file (in ./mylib/src)

// Include guard
#include "message.h"

namespace MyLib
{
    class Request : public Message
    {
    public:
        Request();
        ~Request();

        bool ToString(std::string& rstrOutput);

    private:
        bool Build();

    private:
        bool m_b;
    };
}

response.h file (in ./mylib/src)

// Include guard
#include "message.h"

namespace MyLib
{
    class Response : public Message
    {
    public:
        Response();
        ~Response();

        std::string GetSomething() const;
    };
}

When I distribute my library, I want to let user to #include only one header file (say ./mylib/include/mylib/mylib.h) and use Request and Response. So I've created one big header file like this:

mylib.h file (in ./mylib/include/mylib)

// Include guard
#include <string>

namespace MyLib
{
    class Message
    {
    public:
        Message();
        virtual ~Message() = 0;

        virtual bool ToString(std::string& rstrOutput);
        bool IsEmpty() const;
    };

    class Request : public Message
    {
    public:
        Request();
        ~Request();

        bool ToString(std::string& rstrOutput);
    };

    class Response : public Message
    {
    public:
        Response();
        ~Response();

        std::string GetSomething() const;
    };
}

#endif

But the problem is every time when I make changes to the public parts of my library or add new classes I'll have to update the mylib.h file as well, which is inconvenient. What is a better way to achieve the same thing?

Upvotes: 1

Views: 594

Answers (2)

blackmath
blackmath

Reputation: 252

You can make it lib or dll and the user will only call the public APIs, if you want to provide headers for the users then either ask the user to include everything from /exportFolder for example. or as said in previous comment. Or as you did that big header shall be sufficient. you will not modify it unless some of the related classes changed. which is normal.

Upvotes: 0

Bernhard Kausler
Bernhard Kausler

Reputation: 5267

I would delete the three separate headers from "/src" and use the one public header from "/include" in my implementation files (residing in "/src"), too. During compilation you just have to set the include path correctly to make that work.

Upvotes: 2

Related Questions