Multiply defined function

suggest change

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).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents