When using a dll library, is it necessary to include all of the headers used to build the dll?

StackOverflow https://stackoverflow.com/questions/23652815

  •  22-07-2023
  •  | 
  •  

Question

I have built a shared library (.dll) from a C++ source code.

Now when I want to use this library in another program, do I need to include all of the header files that were used originally for building the library, or including just the headers that belong to used functions in my (new) program suffices? There are many functions in the library that are not used directly in my new program, but, needless to say, all of them are used by the functions in the program.

(So they are indirectly used in the program too, and it would be strange if their inclusion is not necessary.)

Was it helpful?

Solution

Header files are nothing magical, they're just a convenient way of ensuring your .cpp file has access to all the declarations and definitions it needs. So only include those you actually need in each of your files(1).

The above refers to putting #include statements in your files—only do this for header files you actually need to use. Of course, the header files you include can #include other header files themselves.

Like any other well-behaved (i.e., actually usable) DLL, your DLL must supply a set of public interface header files. Under normal circumstances, you must have all these public interface header files available for building a program using that DLL. That doesn't mean you should #include them all; quite on the contrary, you should not. The compiler (preprocessor, actually) will #include what it needs.

Note that when the DLL itself was built, there were probably many more header files involved, but these were private to the implementation and not part of the public interface. You do not need them to build a program using the DLL, and in the general case you don't even have access to them.

So, when designing your own DLL, you must stricly differentiate between public and internal header files. The public header files must be made available to clients, the internal ones need not (unless the client is supposed to build the DLL themselves). Of course, this means a public header file may never #include an internal one.


(1) Note that header file inclusion is purely textual—when reading your source file, the preprocessor effectively copies the contents of the header file and pastes it in place of the #include statement, then goes on parsing. You you did this copy & paste yourself instead, the file would build and run just as well. Of course, it wouldn't pick up later changes in the header file, which is the primary reason why header files are used in the first place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top