multiple definition of '...'
multiple definition of '...'
DodaTech
3 min read
The multiple definition of '...' error means a symbol is defined more than once across translation units. The linker sees multiple definitions and cannot choose.
What It Means
You violated the One Definition Rule (ODR). In C++, every non-inline function and every object can have exactly one definition across the entire program. When you compile multiple source files that each contain a definition, the linker reports a conflict.
Why It Happens
- A function is defined in a header that is included in multiple
.cppfiles - A global variable is defined in a header without
extern - The same source file is compiled twice and both object files are linked
- Missing header guards combined with multiple includes in the same translation unit
- A non-inline function is defined inside a class definition
How to Fix It
Step 1: Separate declarations from definitions
// math.h — declaration only
#ifndef MATH_H
#define MATH_H
int add(int a, int b);
#endif// math.cpp — single definition
#include "math.h"
int add(int a, int b) {
return a + b;
}// main.cpp
#include "math.h"
int main() {
return add(2, 3);
}g++ -c math.cpp -o math.o
g++ -c main.cpp -o main.o
g++ main.o math.o -o programStep 2: Use header guards
// utils.h
#ifndef UTILS_H
#define UTILS_H
int process(int x);
#endifWithout the guard, including utils.h twice in the same file causes redefinition errors.
Step 3: Use inline for functions in headers
// config.h
#ifndef CONFIG_H
#define CONFIG_H
inline int getDefaultPort() {
return 8080;
}
#endifinline allows the same function definition to appear in multiple translation units without violating ODR.
Step 4: Use static or anonymous namespaces
// helper.h — internal linkage, each TU gets its own copy
static int helperFunction(int x) {
return x * 2;
}Or with anonymous namespace (preferred in C++):
namespace {
int helperFunction(int x) {
return x * 2;
}
}Step 5: Use extern for global variables
// globals.h
#ifndef GLOBALS_H
#define GLOBALS_H
extern int globalCounter; // declaration only
#endif// globals.cpp
#include "globals.h"
int globalCounter = 0; // single definition
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro