Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are header-only libraries acceptable?

Personally, I quite like header-only libraries, but there are claims they cause code bloat due to over-inlining (as well as the other obvious problem of longer compile times).

I was wondering, how much truth is there to these claims (the one about bloat)?

Furthermore, are the costs 'justified'? (Obviously there are unavoidable cases such as when it's a library implemented purely or mostly with templates, however I'm more interested in the case where there's actually a choice available.)

I know there's no hard and fast rule, guideline, etc as far as stuff like this goes, but I'm just trying to get a feel for what others think on the issue.

P.S. Yes this is a very vague and subjective question, I'm aware, and so I have tagged it as such.

like image 455
RaptorFactor Avatar asked Feb 01 '10 04:02

RaptorFactor


People also ask

Why are header-only libraries good?

Having a header-only library also means you don't have to worry about different platforms where the library might be used. When you separate the implementation, you usually do so to hide implementation details, and distribute the library as a combination of headers and libraries ( lib , dll 's or . so files).

How does a header-only library work?

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.

Is the C++ Standard Library header-only?

Note the part of the C++ Standard Library which makes use of templates such as <vector> , string> , <map> , etc is header-only library. Actually templates (class templates and function templates) cannot be compiled into static or dynamic library to be linked to programs.


1 Answers

In my experience bloat hasn't been a problem:

  • Header only libraries give compilers greater ability to inline, but they do not force compilers to inline - many compilers treat the inline keyword as nothing more than a command to ignore multiple identical definitions.

  • Compilers usually have options to optimize to control the amount of inlining; /Os on Microsoft's compilers.

  • It's usually better to allow the compiler to manage the speed vs. size issues. You'll only see bloat from calls that have actually been inlined, and the compiler will only inline them if its heuristics indicate that it inlining will improve performance.

I wouldn't consider code bloat as a reason to stay away from header only libraries - but I would urge you to consider how much a header only approach will increase compile times by.

like image 190
JoeG Avatar answered Oct 07 '22 22:10

JoeG