Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) Multiple definition of 'X'

 

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:

 

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.

 

 

 

 

 

 

Technical facts

 

Application type(s)

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: CppLinkErrorMultipleDefinition.pro

 

TEMPLATE = app
CONFIG += console
CONFIG -= qt
SOURCES += \
    main.cpp \
    a.cpp

HEADERS += \
    a.h


 

 

 

 

 

a.h

 

#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

 

 

 

 

 

a.cpp

 

#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


 

 

 

 

 

main.cpp

 

#include "a.h"

int main()
{
  A a;
  a.SayHello();
  a.SayHelloInline();
}

 

 

 

 

 

References

 

  1. 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'
  2. 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'

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml