-2

I understand that in the standard library for C++, they have lots of functions that are not inline. However, by reading multiple other SO questions/answers, I have discovered that having non-inline functions in headers that are included across multiple source files causes multiple definition errors. So how would I do this? I know usually a source file should be used to define non-inline functions, but how is it done? I'd just like to know. And not just in the standard library I know this is used, lots of other libraries also do that, such as, say, boost, among pretty much every other major library.

Sam
  • 7,252
  • 16
  • 46
  • 65
markasoftware
  • 12,292
  • 8
  • 41
  • 69

1 Answers1

3

The relevant rules are found in ยง3.2 [basic.def.odr] of the standard:

  • (p1) No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.
  • (p4) Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required. [...] An inline function shall be defined in every translation unit in which it is odr-used.
  • (p6) There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data member of a class template (14.5.1.3), member function of a class template (14.5.1.1), or template specialization for which some template parameters are not specified (14.7, 14.5.5) in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. [This is followed by one whole page of rules that basically says the definitions must be completely identical.]

In short, to not violate ODR, a "function" defined in a header that's included in multiple translation units must be (1) inline; (2) a function template; or (3) a member of a class template.

T.C.
  • 133,968
  • 17
  • 288
  • 421