C++ One Definition Rule (ODR) Multiply defined function

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

The most important consequence of the One Definition Rule is that non-inline functions with external linkage should only be defined once in a program, although they can be declared multiple times. Therefore, such functions should not be defined in headers, since a header can be included multiple times from different translation units.

foo.h:

#ifndef FOO_H
#define FOO_H
#include <iostream>
void foo() { std::cout << "foo"; }
void bar();
#endif

foo.cpp:

#include "foo.h"
void bar() { std:: cout << "bar"; }

main.cpp:

#include "foo.h"
int main() {
    foo();
    bar();
}

In this program, the function foo is defined in the header foo.h, which is included twice: once from foo.cpp and once from main.cpp. Each translation unit therefore contains its own definition of foo. Note that the include guards in foo.h do not prevent this from happening, since foo.cpp and main.cpp both separately include foo.h. The most likely result of trying to build this program is a link-time error identifying foo as having been multiply defined.

To avoid such errors, one should declare functions in headers and define them in the corresponding .cpp files, with some exceptions (see other examples).



Got any C++ Question?