One Definition Rule
   HOME

TheInfoList



OR:

The One Definition Rule (ODR) is an important rule of the
C++ C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
programming language A programming language is a system of notation for writing computer programs. Most programming languages are text-based formal languages, but they may also be graphical. They are a kind of computer language. The description of a programming ...
that prescribes that classes/structs and non-inline functions cannot have more than one definition in the entire program and template and types cannot have more than one definition by translation unit. It is defined in the ISO C++ Standard (
ISO/IEC 14882 C++ (pronounced "C plus plus") is a high-level general-purpose programming language created by Danish computer scientist Bjarne Stroustrup as an extension of the C programming language, or "C with Classes". The language has expanded significan ...
) 2003, at section 3.2.


Summary

In short, the ODR states that: #In any translation unit, a
template Template may refer to: Tools * Die (manufacturing), used to cut or shape material * Mold, in a molding process * Stencil, a pattern or overlay used in graphic arts (drawing, painting, etc.) and sewing to replicate letters, shapes or designs ...
, type,
function Function or functionality may refer to: Computing * Function key, a type of key on computer keyboards * Function model, a structured representation of processes in a system * Function object or functor or functionoid, a concept of object-oriente ...
, or
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an ...
can have no more than one definition. Some of these can have any number of declarations. A definition provides an instance. #In the entire
program Program, programme, programmer, or programming may refer to: Business and management * Program management, the process of managing several related projects * Time management * Program, a part of planning Arts and entertainment Audio * Progra ...
, an object or non-
inline function In the C and C++ programming languages, an inline function is one qualified with the keyword inline; this serves two purposes: # It serves as a compiler directive that suggests (but does not require) that the compiler substitute the body of th ...
cannot have more than one definition; if an object or function is used, it must have exactly one definition. You can declare an object or function that is never used, in which case you don't have to provide a definition. In no event can there be more than one definition. #Some things, like types, templates, and
extern In the C programming language, an external variable is a variable defined outside any function block. On the other hand, a local (automatic) variable is a variable defined inside a function block. Definition, declaration and the extern keywor ...
inline functions, can be defined in more than one translation unit. For a given entity, each definition must have the same sequence of tokens. Non-extern objects and functions in different translation units are different entities, even if their names and types are the same. Some violations of the ODR must be diagnosed by the
compiler In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs that ...
. Other violations, particularly those that span translation units, are not required to be diagnosed.
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §3.2 One definition rule asic.def.odr' para. 3


Examples

In general, a translation unit shall contain no more than one definition of any class type. In this example, two definitions of the class type C occur in the same translation unit. This typically occurs if a
header file Many programming languages and other computer files have a directive, often called include (sometimes copy or import), that causes the contents of the specified file to be inserted into the original file. These included files are called copybooks ...
is included twice by the same source file without appropriate
header guard In the C (programming language), C and C++ programming languages, an #include guard, sometimes called a macro guard, header guard or file guard, is a particular construct used to avoid the problem of ''double inclusion'' when dealing with the in ...
s. class C ; // first definition of C class C ; // error, second definition of C In the following, forming a pointer to S or defining a function taking a reference to S are examples of legal constructs, because they do not require the type of S to be
complete Complete may refer to: Logic * Completeness (logic) * Completeness of a theory, the property of a theory that every formula in the theory's language or its negation is provable Mathematics * The completeness of the real numbers, which implies t ...
. Therefore, a definition is not required.
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §3.2 One definition rule asic.def.odr' para. 4
Defining an object of type S, a function taking an argument of type S, or using S in a
sizeof sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of ''char''-sized units. Consequently, the construct ''sizeof (char)'' is guaranteed to be ' ...
expression are examples of contexts where S must be complete, and therefore require a definition. struct S; // declaration of S S * p; // ok, no definition required void f(S&); // ok, no definition required void f(S*); // ok, no definition required S f(); // ok, no definition required - this is a function declaration only! S s; // error, definition required sizeof(S); // error, definition required


More than one definition

In certain cases, there can be more than one definition of a type or a template. A program consisting of multiple header files and source files will typically have more than one definition of a type, but not more than one definition per translation unit. If a program contains more than one definition of a type, then each definition must be equivalent.
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §3.2 One definition rule asic.def.odr' para. 5


Definitions of static const data members

In pre-standard C++, all static data members required a definition outside of their class. However, during the C++ standardization process it was decided to lift this requirement for static const integral members. The intent was to allow uses such as: struct C ; char data ::N // N "used" without out-of-class definition without a
namespace In computing, a namespace is a set of signs (''names'') that are used to identify and refer to objects of various kinds. A namespace ensures that all of a given set of objects have unique names so that they can be easily identified. Namespaces ...
scope definition for N. Nevertheless, the wording of the 1998 C++ standard still required a definition if the member was used in the program.
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(1998). '' ISO/IEC 14882:1998(E): Programming Languages - C++ §9.4.2 Static data members lass.static.data' para. 4
This included the member appearing anywhere except as the operand to
sizeof sizeof is a unary operator in the programming languages C and C++. It generates the storage size of an expression or a data type, measured in the number of ''char''-sized units. Consequently, the construct ''sizeof (char)'' is guaranteed to be ' ...
or
typeid In computer programming, run-time type information or run-time type identification (RTTI) is a feature of some programming languages (such as C++, Object Pascal, and Ada) that exposes information about an object's data type at runtime. Run-time typ ...
, effectively making the above ill-formed.
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(1998). '' ISO/IEC 14882:1998(E): Programming Languages - C++ §3.2 One definition rule asic.def.odr' para. 2
This was identified as a defect, and the wording was adjusted to allow such a member to appear anywhere a
constant expression Constant or The Constant may refer to: Mathematics * Constant (mathematics), a non-varying value * Mathematical constant, a special number that arises naturally in mathematics, such as or Other concepts * Control variable or scientific cons ...
is required, without requiring an out-of-class definition. This includes
array An array is a systematic arrangement of similar objects, usually in rows and columns. Things called an array include: {{TOC right Music * In twelve-tone and serial composition, the presentation of simultaneous twelve-tone sets such that the ...
bounds, case expressions, static member initializers, and nontype template arguments.
ISO ISO is the most common abbreviation for the International Organization for Standardization. ISO or Iso may also refer to: Business and finance * Iso (supermarket), a chain of Danish supermarkets incorporated into the SuperBest chain in 2007 * Iso ...
/
IEC The International Electrotechnical Commission (IEC; in French: ''Commission électrotechnique internationale'') is an international standards organization that prepares and publishes international standards for all electrical, electronic and r ...
(2003). '' ISO/IEC 14882:2003(E): Programming Languages - C++ §5.19 Constant expressions xpr.const' para. 1
struct C ; char data ::N // Legal per C++03 template struct D; template<> struct D ; // Legal per C++03 However, using a static const integral member anywhere except where an integral constant-expression is required, requires a definition: struct C ; int main() This requirement was relaxed in a later standard,
C++11 C++11 is a version of the ISO/IEC 14882 standard for the C++ programming language. C++11 replaced the prior version of the C++ standard, called C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by ...
.


Example showing unexpected side effects

We need 4 files: "odr.h", "main.cpp", "odr1.cpp", "odr2.cpp" The acronym "odr" here is short for "One Definition Rule". odr.h: // abstract base class class CBase ; extern CBase *odr1_create(); extern CBase *odr2_create(); main.cpp #include "odr.h" int main(int argc, char **argv) odr1.cpp #include #include "odr.h" class CDummy : public CBase ; CBase *odr1_create() odr2.cpp #include #include "odr.h" class CDummy : public CBase ; CBase *odr2_create() Under a Linux shell to try out, compile with:
g++ -c odr1.cpp
g++ -c odr2.cpp
g++ -c main.cpp
g++ -o odr main.o odr1.o odr2.o
Under a Windows Visual Studio "Build Tools Command Prompt", compile with:
cl /c main.cpp
cl /c odr1.cpp
cl /c odr2.cpp
cl /Feodr.exe main.obj odr1.obj odr2.obj
When executed the expected output is:
odr ONE dummy: Hello
odr TWO dummy: World
But you very likely get:
odr ONE dummy: Hello
odr ONE dummy: Hello
The problem is, that the C++ linker has to figure out how to build the virtual method table for the (two different) "CDummy" classes, and that only works if the class names are different.


See also

*
Include directive Many programming languages and other computer files have a directive, often called include (sometimes copy or import), that causes the contents of the specified file to be inserted into the original file. These included files are called copybooks ...
*
Include guard In the C and C++ programming languages, an #include guard, sometimes called a macro guard, header guard or file guard, is a particular construct used to avoid the problem of ''double inclusion'' when dealing with the include directive. The C ...


References

{{C++ programming language C++ Articles with example C++ code