Thursday, December 10, 2015

C++ headers and sources, templates

Original thread:  http://stackoverflow.com/questions/23962044/multiple-definition-of-first-defined-here-in-the-same-line-in-a-data-struc



If I understand you correctly, you are doing things like this:
// C.h

class C
{
   void f(); // declaration of f; ok to include in many modules
};

// definition of f; must not exist in more than one module
void C::f()
{
}
 
That doesn't work because the definition of f() will wind up in every module that includes C.h, leading to exactly the linker error you describe. You can fix this by either marking f() as inline, or by moving the definition of f() to a separate cpp file.
There is one special case where this is allowed, and that's when f() is a template (either directly or because C is a template). In that case, the definition must be in the header so the compiler can know how to instantiate it for whatever type(s) you specify. This does make life difficult for the linker since you can and often do end up with the sorts of redundant definitions that would normally be errors (e.g if you use f() in more than one module). Special behavior is needed to handle this.
Incidentally, the reason things work when you move the function bodies inside the class definition is because that has the effect of making them implicitly inline.

No comments:

Post a Comment