C++ – Header-only libraries and multiple definition errors

cheadermultiple-definition-error

I want to write a library that to use, you only need to include one header file. However, if you have multiple source files and include the header in both, you'll get multiple definition errors, because the library is both declared and defined in the header. I have seen header-only libraries, in Boost I think. How did they do that?

Best Answer

Declare your functions inline, and put them in a namespace so you don't collide:

namespace fancy_schmancy
{
  inline void my_fn()
  {
    // magic happens
  }
};