Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I consider making a library header-only?

Tags:

Obviously template libraries need to be header only, but for non-templates, when should you make things header-only?

like image 229
Billy ONeal Avatar asked May 28 '11 22:05

Billy ONeal


People also ask

Are header-only libraries good?

For example, header-only libraries sometimes increase code size & compilation times. "Having a header-only library also means you don't have to worry about different platforms where the library might be used": only if you don't have to maintain the library.

How do headers only work in libraries?

In the context of the C or C++ programming languages, a library is called header-only if the full definitions of all macros, functions and classes comprising the library are visible to the compiler in a header file form.

When Should header files be used?

Header File Inclusion Rules A header file should be included only when a forward declaration would not do the job. The header file should be so designed that the order of header file inclusion is not important. The header file inclusion mechanism should be tolerant to duplicate header file inclusions.

What is the difference between header and library?

Header File is the file where all the headers name are mentioned that going to be used or consumed in the main code file. On other hand Library is the file where the implementation code of each header is written down which is mentioned in the Header file.


1 Answers

If you think your non-template library could be header-only, consider dividing it into two files anyway, then providing a third file that includes both the .h and the .cpp (with an include guard).

Then anyone who uses your library in a lot of different TUs, and suspects that this might be costing a lot of compile time, can easily make the change to test it.

Once you know users have the option which way to use the library, the answer probably becomes "offer that option whenever you possibly can". So pretty much any time that including it from multiple TUs wouldn't violate the ODR. For instance, if your non-static free functions refer to static globals, then you're out of luck, since the different definitions of that function in different TUs would refer to different objects by the same name, which is an ODR-violation.

like image 55
Steve Jessop Avatar answered Nov 21 '22 11:11

Steve Jessop