How to define (non-method) functions in header libraries

boost, c++, header, static, warnings

Solution

If you really want to define the function (as opposed to declaring it), you'll need to use `inline` to prevent linker errors.

Otherwise, you can declare the function in the header file and provide its implementation separately in your source file.

Problem

When writing a header library (like Boost), can one define free-floating (non-method) functions without (1) bloating the generated binary and (2) incurring "unused" warnings? When I define a function in a header that's included by multiple source files which in turn is linked into the same binary, the linker complains about redefinitions. One way around this is to make the functions static, but this reproduces the code in each translation unit (BTW, can linkers safely dereplicate these?). Furthermore, this triggers compiler warnings about the function being unused. I was trying to look for an example of a free-floating function in Boost, but I couldn't find one. Is the trick to contain everything in a class (or template)?

Original source