Ah – The One Definition Rule

In response to Scott Meyers’ question on non-inline non-template functions and the one-definition rule, Francis Glassborow replied with a very interesting example of two lexically identical functions that weren’t actually identical.
Try to find the difference:

1
2
3
4
5
6
7
// in file 1:
#include
#include
static int i(0);
void f() {
    std::cout << i;
}
1
2
3
4
5
6
7
// in file 2:
#include
#include
static int i(0);
void f() {
    std::cout << i;
}

The difference between the two, of course, is that the two functions do not refer to the same instance of i: each translation unit has its own definition and, as such, each version of f refers to its own version of i.

When reading this thread on comp.std.c++, this post convinced me that mr Meyers may well have under-estimated the complexity of what he proposed – and that the one definition rule is likely one of the hardest rules to cope with – and one of the rules one is most likely to stumble upon by accident if one doesn’t conciously avoid it – in the C++ programming language.

About rlc

Software Analyst in embedded systems and C++, C and VHDL developer, I specialize in security, communications protocols and time synchronization, and am interested in concurrency, generic meta-programming and functional programming and their practical applications. I take a pragmatic approach to project management, focusing on the management of risk and scope. I have over two decades of experience as a software professional and a background in science.
This entry was posted in C & C++, Software Design and tagged . Bookmark the permalink.