If you want to put function definitions in header files, it appears there are three different solutions:
- mark the function as
inline - mark the function as
static - put the function in an anonymous namespace
(Until recently, I wasn’t even aware of #1.) So what are the differences to these solutions, and when I should I prefer which? I’m in header-only world, so I really need the definitions in the header files.
The
staticand unnamed namespace versions end up being the same: each Translation Unit will contain it’s own version of the function, and that means that given a static functionf, the pointer&fwill be different in each translation unit, and the program will contain N different versions off(more code in the binary).This is not the right approach to provide a function in a header, it will provide N different (exactly equal) functions. If the function contains
staticlocals then there will be N differentstaticlocal variables…EDIT: To make this more explicit: if what you want is to provide the definition of a function in a header without breaking the One Definition Rule, the right approach is to make the function
inline.