I'd like to package a library I'm working on as a header-only library to make it easier for clients to use. (It's small and there's really no reason to put it into a separate translation unit) However, I cannot simply put my code in headers because this violates C++'s one definition rule. (Assuming that the library header is included in multiple translation units of a client project)
How does one modify a library to make it header-only?
Use header guards as Liz suggests and don't forget to put "inline" before your function methods.
ie
Also, I think you'll need to avoid any use of global variables or static variables in your header-only-library code.
You can use the
inline
keyword:inline
allows the linker to simply pick one definition and discard the rest.(As such, if those definitions don't actually match, you get a good dose of undefined behavior...!)
As an aside, member functions defined within a class-type, are implicitly marked
inline
:Use header guards for the parts that compile in one place.