Search code examples
c++dlllinker

Prevent #include of particular headers when a C++ project is built to a DLL?


I'm planning to build a C++ project to a DLL for other C++ projects to use. When building the DLL, as you may assume I want all compiled header objects from the project to be linked into the DLL build. However, I don't want all those headers to be accessible to users of the DLL.

For example, let's say some DLL project has the following headers:

FORFRUITSONLY.h
orange.h
apple.h

orange.h and apple.h both #include FORFRUITSONLY.h or else they wouldn't function. However, I want users of this DLL to only be able to #include orange.h and/or apple.h with the desire for the compiler to fail if they try to #include FORFRUITSONLY.h. How can I achieve this?


Solution

  • My usual approach to this problem is to split the DLL header into two parts, one is a project-internal header and the other the public header meant to be included from other projects.

    The tricky part here is that anything part of the public interface will need to be included.

    For example, if you export a type with a std::string member, then you will need to #include as part of the public header.

    One suggestion would also be to look into the pimpl idiom if you have not already done so, and make the public interface as lean as possible. Unlike with template libraries, the client of a DLL needs no (or at least very limited) knowledge of how the library operates internally.