This post reference to the One Definition Rule.
Wikipedia is pretty bad on explaining how to implement it
Where can I find good ressources about guidelines to follow in C++ .NET?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The one definition rule basically means that a variable/function can only be located at one place in address space of the compiled executable. One way to think of it is while you compile, there is an array of memory to be used in the compiled program (object code), and a lookup table to reference variable/function locations. This is done on a per process level. Suppose that the following is a simple program:
file1.cpp
file2.cpp
When the compiler starts compiling the object code, it reads in the declarations, and puts thing in its table. AT the end of compiling file1.cpp, it will end up with something like this:
This assumes that the function gets compiled to those particular assembly instructions. At linker time, XX XX XX XX will get replaced by the address of someVariable.
File2 ends up something like:
And in this case, the YY will be replaced by the address of square.
That’s where the linker comes into play. The linker’s job is to go through the list, and build up a table of where everything is in the address space of the program at compile time. However, there is a problem if two object files have the same definition of a variable when it tries to link. If there were two definitions of someVariable in the above example, then it wouldn’t know what to replace YY with. Likewise, if there’s no definition, then you get ugly linker errors.
The ‘solution’ to the rule is to partition your file such that you have definitions only in .cpp files, and have declarations of things in your .h files, so the example above would become:
file1.cpp
file1.h
file2.cpp
file2.h
Note that this is an incredibly simple example, and that it doesn’t really apply in .NET since there isn’t a concept of a distinction between a declaration and definition.