Hacker News new | ask | show | jobs
by tobz 3585 days ago
Can someone explain how this is headers-only? C/C++ are not my forte, but my limited interpretation of a "headers only" thing would be more along the lines of: it's only type definitions and preprocessor macros.

It looks like there's plenty of actual method implementations being filled out there, but they just happen to be in a .hpp file instead of a .cpp file.

2 comments

It means all the code is defined in-line in the header file, inside the class definition, instead of the more traditional method of using a header and an associated cpp file.

A lot of the C++ standard library (STL) and Boost are header only (but not all)

This means to use the code, all you need to do is #include the header file wherever you need it, rather than including a header file and either building a separate static/shared library for the cpp file, or including it in your own build.

So that's really convenient.

Another thing that happens is that the by doing this, the compiler can potentially do a lot better job of optimizing the code by inlining parts of the library straight into your calling function.

With static libraries it is possible to get some optimizations like this made at link time, since link time code generation is a requirement for templates, but that's not possible with shared libraries since you are forced to call through an exported function entry point by their very nature.

Header only libraries are typical for containers or light weight libraries where the cost of inclusion and possible code duplication of code is worth the performance gains, and certainly very popular where templates are involved.

tl;dr, header only is cool just because they are so easy to consume and don't need a make file. Just #include and you are done.

Gotcha. Thanks for the detailed explanation.
header-only usually means there's one or more .h/.hpp files that you can include in your source. There's no source file or library to compile and include

e.g. if I had Hello.h and Hello.cpp, you'd need to either add Hello.cpp to your make/build or build a library and link to it.

Header-only version means all you do is

#include "Hello.h"

and you're all set to go.

So in this case, headers-only is really just an approach to avoid compiling a separate library? More akin to literally including the source code in your source code, in the eyes on the compiler. All in the same object/library.
mostly: yes! :)

Also, keep in mind that most of the library is templates, which need to go in the header files.

BTW, most of boost is header-only :) e.g. boost/noncopyable.hpp would give you a header only equivalent of the NoCopy class I wrote.

I've always felt weird about having to include some big-arse library for just using a simple container, so for things like this I prefer to write header-only versions.

Cool. Thanks for the edification.