2

The typical way of writing C++ code is to seperate it in header and (non-header) source files.

I saw a lot of modern C++ libraries that are header-only (e.g. some Boost libraries). Typically these libraries make a lot of use of templates.

Instead of seperating their files into header and source files, they seperate their files into header declarations and header implementations.

So my questions are:

  • Is it just the old fashion way to use source files?

  • When does it make sense to use source files at all?

  • What are the pros and cons for creating a header-only library?

Max
  • 63
  • 1
  • 5
  • 1
    Part of the answer: http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – NathanOliver May 12 '17 at 17:11
  • 2
    It is doubtful that anybody enjoys having to wait for the compiler to compile the same source code over and over and over and over again. But if it can't be done any other way then that's what it takes. – Hans Passant May 12 '17 at 17:17
  • Possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – Richard Critten May 12 '17 at 18:14

1 Answers1

3

They do it because templates cannot be defined in a source file without making life difficult. It also means you don't need to worry about linking anything (so, convenience). That's it.

In general, we use the header/source model to promote re-usability, partial rebuilds, and better code organisation.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055