TITLE: one definition rule and multiple includes (Newsgroups: comp.lang.c++, 13 Oct 98) ???: > >I thought that if I simply declared the global variable in the header, > >I could include this in both files without error. BRASFIELD: Larry Brasfield > No. C++ has something called the "one definition rule". BECKER: Pete Becker Right idea, wrong principle. The "one definition rule" says that when you define the same thing in more than one place the definitions must be "the same". So, for example, you can have two source files: // file1.cpp class C { int i; }; // stuff that uses C goes here... // end of file1.cpp // file2.cpp class C { int i; }; // stuff that uses C goes here... // end of file2.cpp This does not violate the ODR, because the two definitions of C are "the same". In fact, this is the same principle that lets you define a class in a header and #include that header in multiple source files: the class definition is "the same" in all cases. This doesn't tell you whether it's OK to define the same thing multiple times, however. By the way, for those who are wondering why I keep putting "the same" in quotes, it's because the actual requirement is a bit tricky. For example, suppose file2.cpp looked like this: // file2.cpp typedef int local_type; class C { local_type i; }; // stuff that uses C goes here... // end of file2.cpp This definition of C is "the same" as the definition in file1.cpp. VANDEVOORDE: David Vandevoorde , (private email) > BECKER: Pete Becker > > Right idea, wrong principle. The "one definition rule" says that > when you define the same thing in more than one place the definitions > must be "the same". So, for example, you can have two source files: It only says that for certain "things"; e.g. for classes, inline functions and templates. Even then, the "more than one place" must be in different transation units. For non-inline functions and objects with external linkage you cannot define them in multiple places no matter what. (As Pete says, the rules are a bit tricky to word, but they correspond to a system programmer's intuition. I think the goals of the ODR are to (a) enable implementations using traditional UNIX-like linkers, and (b) keep sanity in semantics across translation units.)