Header-only
C/C++ library offered in pure header files
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, with no separate implementation files or precompiled binaries. Header-only libraries do not need to be separately compiled, packaged and installed in order to be used. All that is required is to point the compiler at the location of the headers, and then #include the header files into the application source. Another advantage is that the compiler's optimizer can do a much better job when all the library's source code is available. Because the compiler has direct access to the implementation, it can inline more code, which can make the compiled executable faster.
Compiling the library's code directly allows for more efficient inlining, potentially resulting in faster executable code due to the elimination of function call overheads.
The disadvantages include:
- Brittleness: most changes to the library will require recompilation of all compilation units using that library, which can further increase development time.
- Longer compilation times: the compilation unit must see the implementation of all components in the included files, rather than just their interfaces. This can lead to increased compilation times, especially for large libraries or projects that include the library in multiple files.
- Machine-code bloat: the necessary use of inline statements in non-class functions can lead to code bloat by over-inlining,
- Harder to understand: the header contains both the interface and the implementation whereas traditional library separate both.
Nonetheless, the header-only form is popular because it simplifies code distribution and re-use by avoiding many of the problems associated with packaging and linking external code.
Many header-only libraries offer porting to modules through export extern "C++" over a header, which automatically attaches symbols to the global module, allowing attaching symbols otherwise declared with internal linkage:
export module wikipedia.examples.mylib; export extern "C++" { // Forces the contents in the header to have global module attachment when exported #include <wikipedia/examples/MyLib.hpp> }For C++ templates, including the definitions in header is the only way to compile, since the compiler requires the full definition of the templates in order to instantiate.
Sources and credits
This article is adapted from the Wikipedia article “Header-only”, written by its contributors and licensed under CC BY-SA 4.0. Fathomly has changed the layout, removed citation markers, navigation and maintenance notices, and adjusted punctuation. This adapted version is shared under the same license. For references, see the original article.
Fathomly is not affiliated with or endorsed by the Wikimedia Foundation. Spotted a problem? Tell us.