Multiple definition of 'X' is a link error.
Multiple definition of 'X' is caused when the linker encounters multiple definitions of the same (member) function. For example, see the code below:
#ifndef A_H #define A_H struct A { A(); }; #include <iostream> A::A() { std::cout << "Hi\n"; } #endif // A_H
This header file contains both a declaration and definition of the constructor of class A.
'Huh, but there is an #include guard!', you might think. Correct, this does prevent the compile error 'Redefinition of '. But the (non-inline) definition of the constructor of class A will be present in all translation units that #include this header file.
This is an example of data (in this case a member function) with external linkage. Avoid data with external linkage at file scope [1]. Avoid non-inline function definitions in header files [2].
Some solutions are:
- Put the declarations in header files, put the definitions in implementation files
- Make the declarations inline
- Ensure the header file is used by exactly one unit
The first solution is by far the most common. The latter solution is not always possible.
Below is a full project with this link error.
Operating system(s) or programming environment(s)
Lubuntu 12.10 (quantal)
Qt Creator 2.5.2
- G++ 4.7.2
Libraries used:
STL: GNU ISO C++ Library, version
4.7.2
Qt project file: CppLinkErrorMultipleDefinition.pro
#ifndef A_H #define A_H struct A { A(); void SayHello() const; inline void SayHelloInline() const; }; #include <iostream> //A::A() { std::cout << "Constructor\n"; } //Illegal, cannot put constructor here //void A::SayHello() const { std::cout << "Hello\n"; } //Illegal, cannot put non-inline definition here inline void A::SayHelloInline() const { std::cout << "HelloInline\n"; } #endif // A_H
#include "a.h" A::A() { std::cout << "Constructor\n"; } //Legal, can put constructor here void A::SayHello() const { std::cout << "Hello\n"; } //Legal, can put non-inline definition here
- John Lakos. Large-Scale C++ Software Design. 1996. ISBN: 0-201-63362-0. Chapter 2.3.1, page 70: 'Avoid data with external linkage at file scope'
- Bjarne Stroustrup. The C++ Programming Language (3rd edition). 1997. ISBN: 0-201-88954-4. Section 9.5, item 4: 'Avoid non-inline function definitions in headers'


